post the file
Some checks failed
Dotnet build and test / build (pull_request) Has been cancelled

This commit is contained in:
Paul Schneider 2026-09-18 13:38:42 +01:00
commit bc6bebea06
Signed by: notazof
GPG key ID: 1DD5D838E5343B06
4 changed files with 55 additions and 4 deletions

View file

@ -3,8 +3,10 @@ namespace Yavsc.Api.Helpers
public static class RequestHelpers public static class RequestHelpers
{ {
// Check for some apache proxy header, if any // Check for some apache proxy header, if any
#pragma warning disable CS8632 // L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'.
public static string? ForwardedFor(this HttpRequest request) { public static string? ForwardedFor(this HttpRequest request) {
string? host = request.Headers["X-Forwarded-For"]; string? host = request.Headers["X-Forwarded-For"];
#pragma warning restore CS8632 // L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'.
if (string.IsNullOrEmpty(host)) { if (string.IsNullOrEmpty(host)) {
host = request.Host.Value; host = request.Host.Value;
} else { // Using X-Forwarded-For last address } else { // Using X-Forwarded-For last address

View file

@ -15,10 +15,14 @@ namespace Yavsc.Blogs.Controllers
public class BlogApiController : Controller public class BlogApiController : Controller
{ {
private readonly BlogSpotService blogSpotService; private readonly BlogSpotService blogSpotService;
private readonly ILogger<BlogApiController> logger;
public BlogApiController(BlogSpotService blogSpotService) public BlogApiController(
BlogSpotService blogSpotService,
ILoggerFactory loggerFactory)
{ {
this.blogSpotService = blogSpotService; this.blogSpotService = blogSpotService;
this.logger = loggerFactory.CreateLogger<BlogApiController>();
} }
// GET: api/v1/blogspot // GET: api/v1/blogspot
@ -60,6 +64,7 @@ namespace Yavsc.Blogs.Controllers
var blog = await ReadBlogRequestAsync(); var blog = await ReadBlogRequestAsync();
if (blog is null) if (blog is null)
{ {
logger.LogWarning("PUT /api/v1/blogspot/{id} failed to read blog payload from request body or multipart form.", id);
return BadRequest(ModelState); return BadRequest(ModelState);
} }
@ -79,6 +84,7 @@ namespace Yavsc.Blogs.Controllers
result.MemberNames.FirstOrDefault() ?? string.Empty, result.MemberNames.FirstOrDefault() ?? string.Empty,
result.ErrorMessage ?? "Invalid value."); result.ErrorMessage ?? "Invalid value.");
} }
logger.LogWarning("PUT /api/v1/blogspot/{id} failed validation: {errors}", id, ModelState);
return BadRequest(ModelState); return BadRequest(ModelState);
} }
@ -107,16 +113,27 @@ namespace Yavsc.Blogs.Controllers
var existing = await blogSpotService.GetBlogPostAsync(id); var existing = await blogSpotService.GetBlogPostAsync(id);
if (existing == null) if (existing == null)
{ {
logger.LogWarning("PUT /api/v1/blogspot/{id} failed: blog post not found.", id);
return NotFound(); return NotFound();
} }
try try
{ {
await blogSpotService.Modify(User, blog); await blogSpotService.Modify(User, blog);
blogSpotService.AttachFiles(files, User.GetUserId(), id); logger.LogInformation("PUT /api/v1/blogspot/{id} modified successfully.", id);
if (files.Count > 0)
{
logger.LogInformation("PUT /api/v1/blogspot/{id} attaching {fileCount} files.", id, files.Count);
blogSpotService.AttachFiles(files, User.GetUserId(), id);
}
else
{
logger.LogInformation("PUT /api/v1/blogspot/{id} no files to attach.", id);
}
} }
catch (AuthorizationFailureException) catch (AuthorizationFailureException)
{ {
logger.LogWarning("PUT /api/v1/blogspot/{id} failed: authorization failure.", id);
return Challenge(); return Challenge();
} }

View file

@ -9,6 +9,7 @@ using Yavsc.Models;
using Yavsc.Services; using Yavsc.Services;
using Yavsc.Server.Helpers; using Yavsc.Server.Helpers;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace Yavsc.Blogs; namespace Yavsc.Blogs;
internal class Program internal class Program
@ -22,6 +23,8 @@ internal class Program
var services = builder.Services; var services = builder.Services;
var siteSection = builder.Configuration.GetSection("Site");
services.Configure<SiteSettings>(siteSection);
// MvcBuilder // MvcBuilder
builder.Services builder.Services
.AddAuthorization(options => .AddAuthorization(options =>
@ -79,8 +82,17 @@ internal class Program
options.SetDefaultCulture(supportedCultures[0]) options.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures) .AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures); .AddSupportedUICultures(supportedCultures);
})
.Configure<SiteSettings>(settings =>
{
if (settings.Blog == null)
{
settings.Blog = "blog";
}
}); });
// App startup // App startup
using (var app = builder.Build()) using (var app = builder.Build())
{ {

View file

@ -5,6 +5,7 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Yavsc; using Yavsc;
using Yavsc.Blogspot; using Yavsc.Blogspot;
@ -22,17 +23,24 @@ public class BlogSpotService
private readonly IAuthorizationService _authorizationService; private readonly IAuthorizationService _authorizationService;
private readonly IFileSystemAuthManager fileSystemAuthManager; private readonly IFileSystemAuthManager fileSystemAuthManager;
private readonly SiteSettings siteSettings; private readonly SiteSettings siteSettings;
private readonly ILogger<BlogSpotService> logger;
public BlogSpotService( public BlogSpotService(
ApplicationDbContext context, ApplicationDbContext context,
IAuthorizationService authorizationService, IAuthorizationService authorizationService,
IFileSystemAuthManager fileSystemAuthManager, IFileSystemAuthManager fileSystemAuthManager,
IOptions<SiteSettings> siteSettings) IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory)
{ {
_authorizationService = authorizationService; _authorizationService = authorizationService;
_context = context; _context = context;
this.fileSystemAuthManager = fileSystemAuthManager; this.fileSystemAuthManager = fileSystemAuthManager;
this.siteSettings = siteSettings.Value; this.siteSettings = siteSettings.Value;
if (siteSettings.Value.Blog == null)
{
throw new InvalidOperationException("SiteSettings.Blog is not configured.");
}
this.logger = loggerFactory.CreateLogger<BlogSpotService>();
} }
public void AttachFiles(IFormFileCollection files, string userId, long postId) public void AttachFiles(IFormFileCollection files, string userId, long postId)
@ -52,13 +60,19 @@ public class BlogSpotService
user.UserName, user.UserName,
blogFilesSubdir); blogFilesSubdir);
var di = new DirectoryInfo(destDir); var di = new DirectoryInfo(destDir);
if (!di.Exists) di.Create();
if (!di.Exists)
{
logger.LogInformation("Creating directory for blog attachments: {destDir}", destDir);
di.Create();
}
foreach (var formFile in files) foreach (var formFile in files)
{ {
var fileInfo = user.ReceiveUserFile(destDir, formFile); var fileInfo = user.ReceiveUserFile(destDir, formFile);
if (fileInfo != null && !fileInfo.QuotaOffense) if (fileInfo != null && !fileInfo.QuotaOffense)
{ {
logger.LogInformation("Attached file {fileName} to blog post {postId} for user {userId}.", fileInfo.FileName, postId, userId);
var uploadedFile = new UploadedFile var uploadedFile = new UploadedFile
{ {
Path = fileInfo.FileName, Path = fileInfo.FileName,
@ -74,6 +88,11 @@ public class BlogSpotService
FileId = uploadedFile.Id FileId = uploadedFile.Id
}; };
_context.BlogAttachedFiles.Add(attachment); _context.BlogAttachedFiles.Add(attachment);
logger.LogInformation("Created BlogAttachedFile entry for file {fileName} and blog post {postId}.", fileInfo.FileName, postId);
}
else
{
logger.LogWarning("Failed to attach file {fileName} to blog post {postId} for user {userId}. Quota offense: {quotaOffense}", formFile.FileName, postId, userId, fileInfo?.QuotaOffense);
} }
} }
_context.SaveChanges(userId); _context.SaveChanges(userId);
@ -81,6 +100,7 @@ public class BlogSpotService
catch (Exception ex) catch (Exception ex)
{ {
Debug.WriteLine($"Erreur lors du traitement des fichiers : {ex.Message}"); Debug.WriteLine($"Erreur lors du traitement des fichiers : {ex.Message}");
logger.LogError(ex, "Error while processing attached files for blog post {postId} and user {userId}.", postId, userId);
} }
} }
} }