mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 11:00:06 +01:00
Compare commits
36 Commits
enhanced_c
...
3e823fb37b
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e823fb37b | |||
| 9e9017717a | |||
| bc05e91790 | |||
| df4cd1c8a7 | |||
| f60f613969 | |||
| ceb1829eb9 | |||
| a1086b94f1 | |||
| ba162c34cc | |||
| 197918e526 | |||
| ac80061437 | |||
| e7cebc32a4 | |||
| 9e1e9c86d3 | |||
| 10d2a35e61 | |||
| ca78f43f73 | |||
| 3a82e4291e | |||
| 341755d77e | |||
| 468d502827 | |||
| 0ec7bdf2fe | |||
| b292586764 | |||
| 779772e60c | |||
| b96c780533 | |||
| f773f886b4 | |||
| d502e9d120 | |||
| a8a82df6ed | |||
| d09d8f85e3 | |||
| 05e6b9bc86 | |||
| db6f57830a | |||
| ddfab4dac1 | |||
| d99755e7af | |||
| 1f9c04e2fc | |||
| d53b85fe9e | |||
| 644e9de0bd | |||
| ee7e7762e0 | |||
| 7d20e4d4f9 | |||
| 908a56665d | |||
| 76258bc0eb |
@@ -1,5 +1,5 @@
|
||||
[*]
|
||||
end_of_line = crlf
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.Entities;
|
||||
using QuotifyBE.DTOs;
|
||||
using System.Threading.Tasks;
|
||||
using QuotifyBE.Mapping;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
|
||||
@@ -71,7 +70,7 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
// All set - generate the token and return it
|
||||
var token = guhf.GenerateJwtToken(user);
|
||||
SuccessfulLoginDTO response = user.ToSuccessfulLoginDTO(token);
|
||||
SuccessfulLoginDTO response = user.ToSuccessfulLoginDTO(token, guhf.UserRoleAsStr(user));
|
||||
|
||||
return Ok(response);
|
||||
} else return Unauthorized(new {status = "error", error_msg = "Unknown pair of email and password"});
|
||||
@@ -83,8 +82,11 @@ public class AuthController : ControllerBase
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Dummy, authed endpoint used to test JWTs.
|
||||
/// <br/><br/>
|
||||
/// <b>Important!</b>
|
||||
/// Authed endpoints expect Authorization header, e.g.:
|
||||
/// Authorization: bearer {jwt}</remarks>
|
||||
/// Authorization: bearer {jwt}
|
||||
/// </remarks>
|
||||
/// <returns>Dummy json</returns>
|
||||
/// <response code="200">Returned on request with valid credentials</response>
|
||||
/// <response code="401">Returned on request with invalid JWT</response>
|
||||
@@ -104,8 +106,7 @@ public class AuthController : ControllerBase
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Authed endpoint used to check human-readable user role.
|
||||
/// Authed endpoints expect Authorization header, e.g.:
|
||||
/// Authorization: bearer {jwt}</remarks>
|
||||
/// </remarks>
|
||||
/// <returns>Json containing single field "role"</returns>
|
||||
/// <response code="200">Returned on request with valid credentials</response>
|
||||
/// <response code="400">Returned on request with JWT whose user could not be found (sanity check)</response>
|
||||
@@ -125,4 +126,31 @@ public class AuthController : ControllerBase
|
||||
return Ok(new { Role = guhf.UserRoleAsStr(u) });
|
||||
}
|
||||
|
||||
// GET /api/v1/auth/me
|
||||
/// <summary>
|
||||
/// [AUTHED] Get user info
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Authed endpoint used to get info about the user.
|
||||
/// </remarks>
|
||||
/// <returns>Json containing user info DTO</returns>
|
||||
/// <response code="200">Returned on request with valid credentials</response>
|
||||
/// <response code="400">Returned on request with JWT whose user could not be found (sanity check)</response>
|
||||
[HttpGet("me")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(typeof(UserInfoDTO), 200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||
public IActionResult GetUserData()
|
||||
{
|
||||
// Get user token from Authorization header
|
||||
User? u = guhf.GetUserFromToken(Request.Headers.Authorization!);
|
||||
if (u == null) // sanity check
|
||||
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "User not found" });
|
||||
|
||||
// Return user data as a DTO
|
||||
return Ok(u.ToUserInfoDTO(guhf.UserRoleAsStr(u)));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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,13 +118,16 @@ public class CategoryController : ControllerBase
|
||||
|
||||
}
|
||||
|
||||
|
||||
// POST /api/v1/categories
|
||||
/// <summary>
|
||||
/// [AUTHED] Create a new category
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Allows authorized users to create categories. <br/>
|
||||
/// Important! Category names are case insensitive. <br/>
|
||||
/// Allows authorized users to create categories.
|
||||
/// <br/><br/>
|
||||
/// <b>Important!</b>
|
||||
/// Category names are case insensitive. <br/>
|
||||
/// Has CORS set.
|
||||
/// </remarks>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
@@ -108,4 +163,94 @@ public class CategoryController : ControllerBase
|
||||
|
||||
}
|
||||
|
||||
// DELETE /api/v1/categories
|
||||
/// <summary>
|
||||
/// [AUTHED] Delete a category
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Allows authorized users to delete categories.
|
||||
/// <br/><br/>
|
||||
/// Has CORS set.
|
||||
/// </remarks>
|
||||
/// <param name="id">Id of the category which shall be deleted</param>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
/// <response code="404">Returned when no such category exists</response>
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> DeleteCategory(int id)
|
||||
{
|
||||
// (Attempt to) find the category
|
||||
Category? cat = await _db.Categories
|
||||
.FirstOrDefaultAsync(c => c.Id == id);
|
||||
// Failed?
|
||||
if (cat == null)
|
||||
return NotFound(new { status = "error", error_msg = "Category not found" });
|
||||
|
||||
// Find all the QuoteId <-> CategoryId pairs for provided id
|
||||
List<QuoteCategory> quoteLinks = await _db.QuoteCategories
|
||||
.Where(qc => qc.CategoryId == id)
|
||||
.ToListAsync();
|
||||
|
||||
// For each of the dependent quotes
|
||||
foreach (var link in quoteLinks) {
|
||||
// Remove all the associative pairs
|
||||
_db.QuoteCategories.Remove(link);
|
||||
}
|
||||
|
||||
// Finally, remove the category
|
||||
_db.Categories.Remove(cat);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// Return ok
|
||||
return Ok(new { Status = "ok" });
|
||||
}
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.DTOs;
|
||||
using QuotifyBE.Entities;
|
||||
@@ -32,53 +33,106 @@ public class QuotesController : ControllerBase
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A page of quotes consists of 10 quotes or less.
|
||||
/// If a page does not contain any quotes, 404 is returned.
|
||||
/// Important! Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
|
||||
/// If a page does not contain any quotes, an empty list is returned.
|
||||
/// <br/><br/>
|
||||
/// <b>Important!</b>
|
||||
/// 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>
|
||||
/// <returns>A page (10 quotes)</returns>
|
||||
/// <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>
|
||||
/// <response code="404">Returned when requested page is invalid</response>
|
||||
/// <response code="404">Returned when requested page is invalid (page_no <= 0)</response>
|
||||
[HttpGet("page/{page_no}")]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> GetQuotePage(int page_no)
|
||||
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;
|
||||
|
||||
List<int>? categories;
|
||||
try
|
||||
{
|
||||
categories = category_id?
|
||||
.Split(",")
|
||||
.Select(Int32.Parse)
|
||||
.ToList();
|
||||
} catch
|
||||
{
|
||||
// Try to catch badly formatted requests
|
||||
return BadRequest(new ErrorDTO {
|
||||
Status = "error",
|
||||
Error_msg = "Category_id can be either an integer, or comma separated integers"
|
||||
});
|
||||
}
|
||||
|
||||
if (page_no <= 0)
|
||||
{
|
||||
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
|
||||
}
|
||||
var quotes = await _db.Quotes
|
||||
.Include(q => q.QuoteCategories)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Include(q => q.User)
|
||||
.Include(q => q.Image)
|
||||
.OrderBy(q => q.Id)
|
||||
.Skip((page_no - 1) * PageSize)
|
||||
.Take(PageSize)
|
||||
.ToListAsync();
|
||||
|
||||
var result = quotes
|
||||
.Select(q => q.ToQuoteShortDTO())
|
||||
.ToList();
|
||||
// Paginacja bez filtra
|
||||
var baseQuery = _db.Quotes
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Include(q => q.User)
|
||||
.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;
|
||||
|
||||
// Filtrowanie przed pobraniem strony
|
||||
if (categories != null)
|
||||
{
|
||||
pageQuotes = await orderedQuery
|
||||
.Where(q => q.QuoteCategories!
|
||||
.Any(qc => categories.Contains(qc.CategoryId))
|
||||
//.Any(qc => qc.CategoryId == category_id.Value)
|
||||
)
|
||||
.Skip((page_no - 1) * PageSize)
|
||||
.Take(PageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
pageQuotes = await orderedQuery
|
||||
.Skip((page_no - 1) * PageSize)
|
||||
.Take(PageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
var result = pageQuotes
|
||||
.Select(q => q.ToQuoteShortDTO())
|
||||
.ToList();
|
||||
|
||||
return Ok(result);
|
||||
|
||||
|
||||
}
|
||||
|
||||
// GET /api/v1/quotes/{id}
|
||||
/// <summary>
|
||||
/// Get specified quote summary
|
||||
/// [AUTHED] Get specified quote summary
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// As per project's guidelines, requires a JWT.
|
||||
/// </remarks>
|
||||
/// <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>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
/// <response code="404">Returned when quote id is invalid or simply doesn't exist</response>
|
||||
[HttpGet("{id}")]
|
||||
[Authorize]
|
||||
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> GetQuoteById(int id)
|
||||
@@ -102,16 +156,24 @@ 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
|
||||
@@ -120,13 +182,24 @@ public class QuotesController : ControllerBase
|
||||
// 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();
|
||||
@@ -148,13 +221,13 @@ public class QuotesController : ControllerBase
|
||||
// Attach categories
|
||||
foreach (var categoryId in request.CategoryIds ?? [])
|
||||
{
|
||||
var categoryExists = await _db.Categories.AnyAsync(c => c.Id == categoryId);
|
||||
if (!categoryExists)
|
||||
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found"});
|
||||
Category? category = await _db.Categories.FirstOrDefaultAsync(c => c.Id == categoryId);
|
||||
if (category == null)
|
||||
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found" });
|
||||
|
||||
quote.QuoteCategories.Add(new QuoteCategory
|
||||
{
|
||||
CategoryId = categoryId,
|
||||
Category = category,
|
||||
Quote = quote
|
||||
});
|
||||
}
|
||||
@@ -162,59 +235,322 @@ public class QuotesController : ControllerBase
|
||||
_db.Quotes.Add(quote);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote);
|
||||
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote.ToQuoteShortDTO());
|
||||
}
|
||||
|
||||
// GET /api/v1/quotes/random
|
||||
/// <summary>
|
||||
/// Get a random quote summary
|
||||
/// Draw a random quote
|
||||
/// </summary>
|
||||
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
|
||||
/// <param name="category_id">(Optional) category id to draw from</param>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
/// <response code="404">Returned when no quotes exist</response>
|
||||
/// <response code="204">Returned when no quotes exist matching provided criteria</response>
|
||||
/// <response code="404">Returned when no quotes exist (in the DB)</response>
|
||||
[HttpGet("random")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> GetRandomQuote()
|
||||
public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null)
|
||||
{
|
||||
var totalQuotes = await _db.Quotes.CountAsync();
|
||||
IQueryable<Quote> query = _db.Quotes
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Include(q => q.Image);
|
||||
|
||||
if (category_id.HasValue)
|
||||
{
|
||||
query = query
|
||||
.Where(q => q.QuoteCategories!
|
||||
.Any(qc => qc.CategoryId == category_id.Value)
|
||||
);
|
||||
}
|
||||
|
||||
var totalQuotes = await query.CountAsync();
|
||||
if (totalQuotes == 0)
|
||||
return NotFound(new ErrorDTO { Status = "error", Error_msg = "No quotes to choose from" });
|
||||
{
|
||||
if (category_id.HasValue)
|
||||
return NoContent(); // Brak cytatów w wybranej kategorii
|
||||
else
|
||||
return NotFound(new ErrorDTO { Status = "error", Error_msg = "No quotes to choose from" });
|
||||
}
|
||||
|
||||
var random = new Random();
|
||||
var skip = random.Next(0, totalQuotes);
|
||||
|
||||
var quote = await _db.Quotes
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
var quote = await query
|
||||
.Skip(skip)
|
||||
.Take(1)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (quote == null)
|
||||
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote"});
|
||||
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote" });
|
||||
|
||||
Image? image = null;
|
||||
if (quote.ImageId != 0)
|
||||
{
|
||||
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
|
||||
}
|
||||
// After getting and checking the quote, update the number of draws
|
||||
Statistic s = await _db.Statistics
|
||||
.FirstAsync(s => s.Label == "number_of_draws");
|
||||
s.IValue += 1;
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
var dto = new QuoteShortDTO
|
||||
{
|
||||
Id = quote.Id,
|
||||
Text = quote.Text,
|
||||
Author = quote.Author,
|
||||
ImageUrl = image?.Url,
|
||||
Categories = quote.QuoteCategories?
|
||||
.Select(qc => qc.Category?.Name ?? "")
|
||||
.Where(name => !string.IsNullOrEmpty(name))
|
||||
.ToList() ?? new List<string>()
|
||||
};
|
||||
|
||||
return Ok(dto);
|
||||
return Ok(quote.ToQuoteShortDTO());
|
||||
|
||||
}
|
||||
|
||||
// DELETE /api/v1/quotes/{id}
|
||||
/// <summary>
|
||||
/// [AUTHED] Delete a quote
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deletes a quote, granted it exists. <br/>
|
||||
/// <br/>
|
||||
/// <i>
|
||||
/// Is this the best practice? Marking the quote as hidden is also an option.
|
||||
/// </i> ~eee4
|
||||
/// </remarks>
|
||||
/// <returns>Json with status</returns>
|
||||
/// <param name="id">Quote id which will be deleted</param>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
/// <response code="404">Returned when no such quote exists</response>
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> DeleteQuote(int id)
|
||||
{
|
||||
// (Attempt to) find the quote
|
||||
Quote? quote = await _db.Quotes
|
||||
.FirstOrDefaultAsync(q => q.Id == id);
|
||||
// Failed?
|
||||
if (quote == null)
|
||||
return NotFound(new { status = "error", error_msg = "Quote not found" });
|
||||
|
||||
// If succeded, remove the quote
|
||||
_db.Quotes.Remove(quote);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// ====================================================================== //
|
||||
// Important! //
|
||||
// Is this the best we can do? Won't marking the quote as "hidden" //
|
||||
// be better than explicitly deleting it? ~eee4 //
|
||||
// ====================================================================== //
|
||||
|
||||
// Return ok
|
||||
return Ok(new { Status = "ok" });
|
||||
}
|
||||
|
||||
// PATCH /api/v1/quotes/{id}
|
||||
/// <summary>
|
||||
/// [AUTHED] Modify an existing quote
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Modifies an existing quote.
|
||||
/// <br/><br/>
|
||||
/// <b>Warning!</b>
|
||||
/// We don't check the user id which created the quote.
|
||||
/// In case of single-user instances, this should not be a problem.
|
||||
/// This might become one, if we want users with non-admin roles;
|
||||
/// that would need some proper ACL checks here (with the help of GUHF).
|
||||
/// <br/><br/>
|
||||
/// <b>Important!</b>
|
||||
/// Image handling works the same as with creating new quote.
|
||||
/// This means that images not present in the DB will be added automatically.
|
||||
/// <br/><br/>
|
||||
/// <b>Important!</b>
|
||||
/// "categories = null" is not the same as "categories = []"!
|
||||
/// 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. 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]
|
||||
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
public async Task<IActionResult> EditQuote(int id, [FromBody] QuoteShortDTO updatedQuote)
|
||||
{
|
||||
// Try to find the quote in question
|
||||
Quote? quote = await _db.Quotes
|
||||
.Include(q => q.QuoteCategories)
|
||||
.FirstOrDefaultAsync(q => q.Id == id);
|
||||
|
||||
// Failed?
|
||||
if (quote == null)
|
||||
return NotFound(new { status = "error", error_msg = "Quote not found" });
|
||||
|
||||
// Is quote contents or author empty?
|
||||
if (string.IsNullOrWhiteSpace(updatedQuote.Text) || string.IsNullOrWhiteSpace(updatedQuote.Author))
|
||||
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Text and author are required." });
|
||||
|
||||
// Alter the quote's content
|
||||
quote.Text = updatedQuote.Text;
|
||||
quote.Author = updatedQuote.Author;
|
||||
quote.LastUpdatedAt = DateTime.UtcNow;
|
||||
|
||||
// Try to find the image inside the DB
|
||||
Image? image = null;
|
||||
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();
|
||||
}
|
||||
}
|
||||
quote.Image = image;
|
||||
|
||||
// Don't touch categories if they are explicitly null
|
||||
if (updatedQuote.Categories == null) { }
|
||||
// If they aren't
|
||||
else if (updatedQuote.Categories.Any())
|
||||
{
|
||||
// Get all the categories associated with a quote from DB
|
||||
List<Category> categoriesFromDb = await _db.Categories
|
||||
.Where(c => updatedQuote.Categories.Contains(c.Name))
|
||||
.ToListAsync();
|
||||
|
||||
// Determine which ones are already present, and which to add
|
||||
IEnumerable<string> existingNames = categoriesFromDb
|
||||
.Select(c => c.Name);
|
||||
List<string> newNames = updatedQuote.Categories
|
||||
.Except(existingNames)
|
||||
.ToList();
|
||||
|
||||
// For all the categories not present
|
||||
foreach (var name in newNames)
|
||||
{
|
||||
// Add them to the DB
|
||||
var newCat = new Category
|
||||
{
|
||||
Name = name,
|
||||
Description = string.Empty,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
_db.Categories.Add(newCat);
|
||||
categoriesFromDb.Add(newCat);
|
||||
}
|
||||
|
||||
// If any categories were added, save changes
|
||||
if (newNames.Any())
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// Assign all the new categories to the quote
|
||||
quote.QuoteCategories = categoriesFromDb
|
||||
.Select(cat => new QuoteCategory
|
||||
{
|
||||
CategoryId = cat.Id,
|
||||
QuoteId = quote.Id
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
// No categories (empty list) inside DTO?
|
||||
// Clear them all!
|
||||
quote.QuoteCategories.Clear();
|
||||
}
|
||||
|
||||
// Save changes, return new quote as a DTO
|
||||
await _db.SaveChangesAsync();
|
||||
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 });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,41 +1,60 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.DTOs;
|
||||
using QuotifyBE.Entities;
|
||||
using QuotifyBE.Mapping;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace QuotifyBE.Controllers
|
||||
{
|
||||
public class Seed : Controller
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
private readonly GeneralUseHelpers guhf;
|
||||
|
||||
public Seed(ApplicationDbContext db, GeneralUseHelpers GUHF)
|
||||
{
|
||||
_db = db;
|
||||
guhf = GUHF;
|
||||
}
|
||||
public async Task SeedAsync()
|
||||
{
|
||||
var AccountNum = await _db.Users.CountAsync();
|
||||
if (AccountNum == 0)
|
||||
{
|
||||
var Admin = new User
|
||||
{
|
||||
Name="admin",
|
||||
Email = "admin@mail.com",
|
||||
// hashed twice, once by frontend, and second time by backend
|
||||
PasswordHash = guhf.HashWithSHA512(guhf.HashWithSHA512("admin")),
|
||||
Role = 0 // role 0 - greatest power, admin, role 0 > role 1
|
||||
};
|
||||
_db.Users.Add(Admin);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.DTOs;
|
||||
using QuotifyBE.Entities;
|
||||
using QuotifyBE.Mapping;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace QuotifyBE.Controllers
|
||||
{
|
||||
public class Seed : Controller
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
private readonly GeneralUseHelpers guhf;
|
||||
|
||||
public Seed(ApplicationDbContext db, GeneralUseHelpers GUHF)
|
||||
{
|
||||
_db = db;
|
||||
guhf = GUHF;
|
||||
}
|
||||
public async Task SeedAsync()
|
||||
{
|
||||
Console.WriteLine($"You're running QuotifyBE, commit {ThisAssembly.Git.Commit} of branch {ThisAssembly.Git.Branch} ({ThisAssembly.Git.CommitDate})\n");
|
||||
|
||||
// Create a user account if no exist
|
||||
var AccountNum = await _db.Users.CountAsync();
|
||||
if (AccountNum == 0)
|
||||
{
|
||||
var Admin = new User
|
||||
{
|
||||
Name="admin",
|
||||
Email = "admin@mail.com",
|
||||
// hashed twice, once by frontend, and second time by backend
|
||||
PasswordHash = guhf.HashWithSHA512(guhf.HashWithSHA512("admin")),
|
||||
Role = 0 // role 0 - greatest power, admin, role 0 > role 1
|
||||
};
|
||||
_db.Users.Add(Admin);
|
||||
await _db.SaveChangesAsync();
|
||||
Console.WriteLine("[QuotifyBE] Administrator user account added!\nDefault credentials are: admin@mail.com, password: admin");
|
||||
}
|
||||
|
||||
// Create sitewide statistic - number of draws
|
||||
Statistic? numOfDraws = await _db.Statistics
|
||||
.FirstOrDefaultAsync(s => s.Label == "number_of_draws");
|
||||
if (numOfDraws == null)
|
||||
{
|
||||
Statistic newRow = new Statistic
|
||||
{
|
||||
Label = "number_of_draws",
|
||||
IValue = 0
|
||||
};
|
||||
_db.Statistics.Add(newRow);
|
||||
await _db.SaveChangesAsync();
|
||||
Console.WriteLine("[QuotifyBE] Sitewide statistic for number of draws added!");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
59
Controllers/StatisticController.cs
Normal file
59
Controllers/StatisticController.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using QuotifyBE.Data;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
|
||||
namespace QuotifyBE.Controllers;
|
||||
|
||||
|
||||
[ApiController]
|
||||
[EnableCors]
|
||||
[Route("api/v1/stats")]
|
||||
[Produces("application/json")]
|
||||
public class StatisticsController : ControllerBase
|
||||
{
|
||||
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
public StatisticsController( ApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
// GET /api/v1/stats
|
||||
/// <summary>
|
||||
/// Return server statistics
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Provides, info on last commit # and date, branch name,
|
||||
/// sitewide stats (number of draws) and available endpoints
|
||||
/// (machine-friendly json).
|
||||
/// <br/>
|
||||
/// Has CORS set.
|
||||
/// </remarks>
|
||||
/// <returns>Dummy json</returns>
|
||||
// /// <response code="200">Returned on request with valid credentials</response>
|
||||
// /// <response code="401">Returned on request with invalid JWT</response>
|
||||
[HttpGet]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(200)]
|
||||
// [ProducesResponseType(401)]
|
||||
public IActionResult GetStats()
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
version = new
|
||||
{
|
||||
lastCommit = ThisAssembly.Git.Commit,
|
||||
lastUpdatedAt = ThisAssembly.Git.CommitDate,
|
||||
currentBranch = ThisAssembly.Git.Branch
|
||||
},
|
||||
endpointDiscovery = "/swagger/v1/swagger.json",
|
||||
sitewideStats = new
|
||||
{
|
||||
numberOfDraws = _db.Statistics.First(s => s.Label == "number_of_draws").IValue
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
119
Controllers/UserContentController.cs
Normal file
119
Controllers/UserContentController.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
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]
|
||||
[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 is returned on success.<br/>
|
||||
/// </remarks>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
/// <response code="400">Returned when file extension is unknown</response>
|
||||
/// <response code="406">Returned when request does not follow user-provided config</response>
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 406)]
|
||||
public IActionResult PostNewImage(IFormFile file)
|
||||
{
|
||||
|
||||
// Ideally, a hash of the file would be stored somewhere
|
||||
// in the database to have a basic redundancy check,
|
||||
// but this will do for now. ~eee4
|
||||
|
||||
// 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",
|
||||
Error_msg = $"Unknown file extension. Please use one of the following: {string.Join(", ", allowedExtensions)}"
|
||||
});
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// https://www.youtube.com/watch?v=6-FNejMrVuk
|
||||
|
||||
// Sprawdź, czy plik spełnia ograniczenia:
|
||||
// 1. Czy rozmiar jest mniejszy od _appsettings["UserContent"]["MaxFileSize"] ?
|
||||
|
||||
|
||||
// Jeśli nie, zwróć ErrorDTO ze wiadomością: $"File size exceeds {_appsettings["UserContent"]["MaxFileSize"]}"
|
||||
|
||||
|
||||
// Zapisz plik na dysku z pseudolosową nazwą GUID
|
||||
|
||||
|
||||
// Wrzucić go do folderu "uploads/images/"
|
||||
|
||||
|
||||
// Stwórz URL postaci: "/uploads/images/<nazwa pliku>.<rozszerzenie>"
|
||||
|
||||
|
||||
// Zwróć powyższy URL
|
||||
return Ok(new { Status = "ok", Filepath = "miejsce na wspomniany URL" });
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ public record class QuoteShortDTO
|
||||
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 List<string>? Categories { get; set; } = new();
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -6,5 +6,6 @@ public record class UserInfoDTO
|
||||
required public string Name { get; set; }
|
||||
required public string Email { get; set; }
|
||||
public int Role { get; set; }
|
||||
public string? RoleName { get; set; }
|
||||
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@ namespace QuotifyBE.Data
|
||||
public DbSet<Category> Categories => Set<Category>();
|
||||
public DbSet<Image> Images => Set<Image>();
|
||||
public DbSet<QuoteCategory> QuoteCategories => Set<QuoteCategory>();
|
||||
public DbSet<Statistic> Statistics => Set<Statistic>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
@@ -25,6 +26,10 @@ namespace QuotifyBE.Data
|
||||
|
||||
builder.Entity<QuoteCategory>()
|
||||
.HasKey(vs => new { vs.QuoteId, vs.CategoryId });
|
||||
|
||||
builder.Entity<Statistic>(e => {
|
||||
e.HasIndex(e => e.Label).IsUnique();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace QuotifyBE.Entities
|
||||
namespace QuotifyBE.Entities
|
||||
{
|
||||
public class Image
|
||||
{
|
||||
|
||||
9
Entities/Statistic.cs
Normal file
9
Entities/Statistic.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace QuotifyBE.Entities;
|
||||
|
||||
public class Statistic
|
||||
{
|
||||
public int Id { get; set; }
|
||||
required public string Label { get; set; }
|
||||
public int? IValue { get; set; }
|
||||
public string? SValue { get; set; }
|
||||
}
|
||||
@@ -5,18 +5,18 @@ namespace QuotifyBE.Mapping;
|
||||
|
||||
public static class UserMapping
|
||||
{
|
||||
public static SuccessfulLoginDTO ToSuccessfulLoginDTO(this User user, string token)
|
||||
public static SuccessfulLoginDTO ToSuccessfulLoginDTO(this User user, string token, string? roleName)
|
||||
{
|
||||
|
||||
return new SuccessfulLoginDTO
|
||||
{
|
||||
Status = "ok",
|
||||
Token = token,
|
||||
User = user.ToUserInfoDTO()
|
||||
User = user.ToUserInfoDTO(roleName)
|
||||
};
|
||||
}
|
||||
|
||||
public static UserInfoDTO ToUserInfoDTO(this User user)
|
||||
public static UserInfoDTO ToUserInfoDTO(this User user, string? roleName)
|
||||
{
|
||||
|
||||
return new UserInfoDTO
|
||||
@@ -24,7 +24,8 @@ public static class UserMapping
|
||||
Id = user.Id,
|
||||
Name = user.Name,
|
||||
Email = user.Email,
|
||||
Role = user.Role
|
||||
Role = user.Role,
|
||||
RoleName = roleName
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
216
Migrations/20250721081641_sitewide_statistics.Designer.cs
generated
Normal file
216
Migrations/20250721081641_sitewide_statistics.Designer.cs
generated
Normal file
@@ -0,0 +1,216 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using QuotifyBE.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace QuotifyBE.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20250721081641_sitewide_statistics")]
|
||||
partial class sitewide_statistics
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Category", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<DateTime?>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Categories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Image", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Url")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Images");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Author")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("ImageId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTime>("LastUpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("UserId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ImageId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("Quotes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.QuoteCategory", b =>
|
||||
{
|
||||
b.Property<int>("QuoteId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("CategoryId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("QuoteId", "CategoryId");
|
||||
|
||||
b.HasIndex("CategoryId");
|
||||
|
||||
b.ToTable("QuoteCategories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Statistic", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<int?>("IValue")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Label")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("SValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Label")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Statistics");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.User", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Role")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
|
||||
{
|
||||
b.HasOne("QuotifyBE.Entities.Image", "Image")
|
||||
.WithMany()
|
||||
.HasForeignKey("ImageId");
|
||||
|
||||
b.HasOne("QuotifyBE.Entities.User", "User")
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Image");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.QuoteCategory", b =>
|
||||
{
|
||||
b.HasOne("QuotifyBE.Entities.Category", "Category")
|
||||
.WithMany()
|
||||
.HasForeignKey("CategoryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("QuotifyBE.Entities.Quote", "Quote")
|
||||
.WithMany("QuoteCategories")
|
||||
.HasForeignKey("QuoteId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Category");
|
||||
|
||||
b.Navigation("Quote");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
|
||||
{
|
||||
b.Navigation("QuoteCategories");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
43
Migrations/20250721081641_sitewide_statistics.cs
Normal file
43
Migrations/20250721081641_sitewide_statistics.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace QuotifyBE.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class sitewide_statistics : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Statistics",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
Label = table.Column<string>(type: "text", nullable: false),
|
||||
IValue = table.Column<int>(type: "integer", nullable: true),
|
||||
SValue = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Statistics", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Statistics_Label",
|
||||
table: "Statistics",
|
||||
column: "Label",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Statistics");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,32 @@ namespace QuotifyBE.Migrations
|
||||
b.ToTable("QuoteCategories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.Statistic", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<int?>("IValue")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Label")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("SValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Label")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Statistics");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("QuotifyBE.Entities.User", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
|
||||
10
Program.cs
10
Program.cs
@@ -33,7 +33,9 @@ builder.Services.AddCors(options =>
|
||||
{
|
||||
policy
|
||||
.WithOrigins(CorsOrigins.ToArray())
|
||||
.AllowAnyHeader(); // this might not be the greatest idea
|
||||
// this might not be the greatest idea:
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,7 +54,11 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
ValidAudience = DomainName,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(JwtSecret)
|
||||
)
|
||||
),
|
||||
// disable clock skew
|
||||
// https://stackoverflow.com/a/46231102
|
||||
// https://stackoverflow.com/a/47155318
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
<UserSecretsId>b302b0ab-745f-4b53-b32a-12fbbc3e622d</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DockerfileContext>.</DockerfileContext>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);1591</NoWarn>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="GitInfo" Version="3.5.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.18" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="8.0.18" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.7" />
|
||||
@@ -25,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="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"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user