11 Commits

8 changed files with 116 additions and 21 deletions

3
.gitignore vendored
View File

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

View File

@@ -80,20 +80,21 @@ public class CategoryController : ControllerBase
// GET /api/v1/categories
/// <summary>
/// [AUTHED] Get every category
/// 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.
/// Can (and will) return an empty list if no categories are found in DB. <br/><br/>
/// <s>Unlike GET /api/v1/categories/page/..., requires authorization with a JWT.</s>
/// Not the case anymore, as choosing a quote from a category requires the user to know
/// of existing categories.<br/><br/>
/// Has CORS set.
/// </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(List<CategoryShortDTO>), 200)]
public async Task<IActionResult> GetQuotePage()
public async Task<IActionResult> GetEveryCategory()
{
// The following seems to be a bad idea, so I leave it as is. ~eee4
//

View File

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

View File

@@ -20,11 +20,13 @@ public class QuotesController : ControllerBase
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
private readonly IConfiguration _appsettings;
public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF)
public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF, IConfiguration appsettings)
{
_db = db;
guhf = GUHF;
_appsettings = appsettings;
}
// GET /api/v1/quotes
@@ -46,7 +48,7 @@ public class QuotesController : ControllerBase
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")]
[EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
[ProducesResponseType(typeof(List<QuoteCompleteDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no = 1, string? sort = "desc", [FromQuery] string? category_id = null)
{
@@ -113,7 +115,7 @@ public class QuotesController : ControllerBase
}
var result = pageQuotes
.Select(q => q.ToQuoteShortDTO())
.Select(q => q.ToQuoteCompleteDTO())
.ToList();
return Ok(result);
@@ -125,15 +127,14 @@ public class QuotesController : ControllerBase
/// [AUTHED] Get specified quote summary
/// </summary>
/// <remarks>
/// As per project's guidelines, requires a JWT.
/// <s>As per project's guidelines, requires a JWT.</s> We need this endpoint to check previous draws for draw history.
/// </remarks>
/// <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(QuoteCompleteDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuoteById(int id)
{
@@ -148,7 +149,7 @@ public class QuotesController : ControllerBase
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
return Ok(quote.ToQuoteShortDTO());
return Ok(quote.ToQuoteCompleteDTO());
}
// POST /api/v1/quotes/new
@@ -386,6 +387,7 @@ public class QuotesController : ControllerBase
// Try to find the quote in question
Quote? quote = await _db.Quotes
.Include(q => q.QuoteCategories)
.Include(q => q.Image)
.FirstOrDefaultAsync(q => q.Id == id);
// Failed?
@@ -536,6 +538,8 @@ public class QuotesController : ControllerBase
request.CustomPrompt, request.Model, request.Temperature, request.CategoryId, request.UseSampleQuote
);
string llmUsed = request.Model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
// Check if any errors occurred
if (generatedResponse == null)
{
@@ -550,7 +554,7 @@ public class QuotesController : ControllerBase
return StatusCode(500, new ErrorDTO { Status = "error", Error_msg = "Unexpected API response" });
// Otherwise, return the response
return Ok(new { Status = "ok", BotResponse = llmResponse });
return Ok(new { Status = "ok", BotResponse = llmResponse, Model = llmUsed });
}
}

View File

@@ -20,6 +20,7 @@ public class UserContentController : ControllerBase
private readonly IConfiguration _appsettings;
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
List<string> _allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
public UserContentController(IConfiguration appsettings, ApplicationDbContext db, GeneralUseHelpers GUHF)
{
@@ -86,15 +87,14 @@ public class UserContentController : ControllerBase
}
// 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))
if (!_allowedExtensions.Contains(fileExtension))
{
return StatusCode(415, new ErrorDTO
{
Status = "error",
Error_msg = $"Unknown file extension. Allowed: {string.Join(", ", allowedExtensions)}"
Error_msg = $"Unknown file extension. Allowed: {string.Join(", ", _allowedExtensions)}"
});
}
@@ -149,14 +149,46 @@ public class UserContentController : ControllerBase
});
}
// GET /api/v1/uc/restrictions
/// <summary>
/// [AUTHED] Get server restrictions for file upload
/// </summary>
/// <remarks>
/// Returns a list of allowed file extensions and mimetypes for upload.
/// </remarks>
/// <response code="200">Returned on valid request</response>
[HttpGet("restrictions")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
public IActionResult GetFileUploadRestrictions()
{
return Ok(new
{
Status = "ok",
AllowedMimeTypes = new List<string>
{
"image/" // this could be done dynamically ~eee4
},
AllowedExtensions = _allowedExtensions,
MaxFileSize = int.TryParse(_appsettings.GetSection("UserContent")["MaxFileSize"], out int r)
? r
: 5 * 1024 * 1024
});
}
// DELETE /api/v1/uc/images/{id}
/// <summary>
/// [AUTHED] Delete an image
/// </summary>
/// <remarks>
/// Deletes an image, granted it exists. <br/>
/// Deletes an image, granted it exists.
/// <br/><br/>
/// <b>Note</b>:
/// If the image is a file on disk, it's also deleted.
/// <br/><br/>
/// <b>Warning</b>:
/// Any reference to deleted image in Quotes table will also be deleted (nullified).
/// </remarks>
/// <returns>Json with status</returns>
/// <param name="id">Image id which will be deleted</param>
@@ -189,6 +221,18 @@ public class UserContentController : ControllerBase
}
// - from db
// - first, from any quotes that reference it
List<Quote> quotesToModify = await _db.Quotes
.Include(q => q.Image)
.Where(q => q.Image == image)
.ToListAsync();
foreach (Quote quote in quotesToModify)
{
quote.Image = null;
}
// - finally, from images table
_db.Images.Remove(image);
await _db.SaveChangesAsync();

View File

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

14
DTOs/QuoteCompleteDTO.cs Normal file
View File

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

View File

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