refacto site settings
Some checks failed
Dotnet build and test / build (pull_request) Failing after 11m10s

This commit is contained in:
Paul Schneider 2026-09-17 22:22:18 +01:00
commit 8faabbb5ff
Signed by: notazof
GPG key ID: 1DD5D838E5343B06
28 changed files with 256 additions and 224 deletions

View file

@ -7,8 +7,6 @@ namespace Yavsc.Server.Helpers
{
public static class AbstractFileSystemHelpers
{
public static string UserBillsDirName { set; get; }
public static string UserFilesDirName { set; get; }
/// <summary>
/// Is Valid this Path?
@ -64,17 +62,6 @@ namespace Yavsc.Server.Helpers
return sb.ToString();
}
public static UserDirectoryInfo GetUserFiles(string userId, string subdir)
{
UserDirectoryInfo di = new UserDirectoryInfo(UserFilesDirName, userId, subdir);
return di;
}
public static bool IsRegularFile(string userName, string subdir)
{
FileInfo fi = new FileInfo( Path.Combine(Path.Combine(UserFilesDirName, userName), subdir));
return fi.Exists;
}
// Server side only supports POSIX file systems
public const char RemoteDirectorySeparator = '/';

View file

@ -35,6 +35,7 @@ namespace Yavsc.ApiControllers
private readonly ILogger logger;
private readonly IBillingService billingService;
private readonly SiteSettings siteSettings;
public BillingController(
IAuthorizationService authorizationService,
@ -43,7 +44,8 @@ namespace Yavsc.ApiControllers
ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
IBillingService billingService
IBillingService billingService,
IOptions<SiteSettings> siteSettings
)
{
_googleSettings=googleSettings.Value;
@ -53,6 +55,7 @@ namespace Yavsc.ApiControllers
this._localizer = SR;
_GCMSender=GCMSender;
this.billingService=billingService;
this.siteSettings = siteSettings.Value;
}
[HttpGet("facture-{billingCode}-{id}.pdf"), Authorize]
@ -65,7 +68,7 @@ namespace Yavsc.ApiControllers
return new ChallengeResult();
}
var fi = bill.GetBillInfo(billingService);
var fi = bill.GetBillInfo(billingService, siteSettings);
if (!fi.Exists) return Ok(new { Error = "Not generated" });
return File(fi.OpenRead(), "application/x-pdf", fi.Name);
@ -229,7 +232,7 @@ namespace Yavsc.ApiControllers
}
if (Request.Form.Files.Count!=1)
return new BadRequestResult();
await User.ReceiveProSignatureAsync(billingCode,id,Request.Form.Files[0],"pro");
await User.ReceiveProSignatureAsync(billingCode,id,Request.Form.Files[0],"pro", siteSettings);
estimate.ProviderValidationDate = DateTime.UtcNow;
dbContext.SaveChanges(User.GetUserId());
// Notify the client
@ -273,7 +276,7 @@ namespace Yavsc.ApiControllers
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
FileInfo fi = new FileInfo(Path.Combine(siteSettings.Bills, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
}
@ -310,7 +313,7 @@ namespace Yavsc.ApiControllers
}
if (Request.Form.Files.Count!=1)
return new BadRequestResult();
await User.ReceiveProSignatureAsync(billingCode,id,Request.Form.Files[0],"cli");
await User.ReceiveProSignatureAsync(billingCode,id,Request.Form.Files[0],"cli", siteSettings);
estimate.ClientValidationDate = DateTime.UtcNow;
dbContext.SaveChanges(User.GetUserId());
return Ok (new { ClientValidationDate = estimate.ClientValidationDate });
@ -327,9 +330,9 @@ namespace Yavsc.ApiControllers
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
FileInfo fi = new FileInfo(Path.Combine(siteSettings.Bills, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
return File(fi.OpenRead(), "application/x-pdf", filename);
}
/// <summary>
@ -405,7 +408,8 @@ namespace Yavsc.ApiControllers
FileReceivedInfo fi;
try
{
fi = await User.ReceiveEstimateSignatureAsync(id, type, payload, token);
fi = await User.ReceiveEstimateSignatureAsync(id, type, payload,
siteSettings, token);
}
catch (Exception ex)
{

View file

@ -2,13 +2,13 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using ImageMagick;
using Yavsc.Models;
using Yavsc.Api.Helpers;
using Yavsc.Server.Helpers;
using System.Diagnostics;
using Microsoft.Extensions.Options;
namespace Yavsc.WebApi.Controllers
{
@ -28,13 +28,16 @@ namespace Yavsc.WebApi.Controllers
];
readonly ApplicationDbContext _dbContext;
private readonly SiteSettings siteSettings;
private readonly ILogger _logger;
public ApiAccountController(
ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
ILoggerFactory loggerFactory, ApplicationDbContext dbContext,
IOptions<SiteSettings> siteSettings)
{
_logger = loggerFactory.CreateLogger(nameof(ApiAccountController));
_dbContext = dbContext;
this.siteSettings = siteSettings.Value;
}
[HttpGet("me")]
@ -146,7 +149,7 @@ namespace Yavsc.WebApi.Controllers
try
{
var info = user.ReceiveAvatar(avatarFile);
var info = user.ReceiveAvatar(avatarFile, siteSettings);
await _dbContext.SaveChangesAsync();
return Ok(new
{

View file

@ -21,7 +21,6 @@ internal class Program
var builder = WebApplication.CreateBuilder(args);
builder.AddConfiguration("api");
Config.SiteSetup = builder.Configuration.GetSection("Site").Get<SiteSettings>() ?? new SiteSettings();
var services = builder.Services;

View file

@ -5,7 +5,9 @@
"CorsAllowedOrigins": [
"https://yavsc.pschneider.fr",
"https://blogs.pschneider.fr"
]
],
"Bills": "bills",
"TempDir": "temp"
},
"Logging": {
"LogLevel": {

View file

@ -338,10 +338,9 @@ public sealed class BlogApiTests : IClassFixture<BlogsWebServerFixture>
ResetAndSeedDefaultUser();
using var http = NewClient(subject: "tester");
var previousRoot = AbstractFileSystemHelpers.UserFilesDirName;
var previousRoot = "blog";
var tempRoot = Path.Combine(Path.GetTempPath(), "yavsc-blogs-tests-files-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
AbstractFileSystemHelpers.UserFilesDirName = tempRoot;
try
{
@ -405,7 +404,6 @@ public sealed class BlogApiTests : IClassFixture<BlogsWebServerFixture>
}
finally
{
AbstractFileSystemHelpers.UserFilesDirName = previousRoot;
try { Directory.Delete(tempRoot, recursive: true); } catch { }
}
}
@ -480,10 +478,9 @@ public sealed class BlogApiTests : IClassFixture<BlogsWebServerFixture>
ResetAndSeedDefaultUser();
using var http = NewClient(subject: "tester");
var previousRoot = AbstractFileSystemHelpers.UserFilesDirName;
var previousRoot = "blog";
var tempRoot = Path.Combine(Path.GetTempPath(), "yavsc-blogs-tests-files-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
AbstractFileSystemHelpers.UserFilesDirName = tempRoot;
try
{
@ -578,7 +575,6 @@ public sealed class BlogApiTests : IClassFixture<BlogsWebServerFixture>
}
finally
{
AbstractFileSystemHelpers.UserFilesDirName = previousRoot;
try { Directory.Delete(tempRoot, recursive: true); } catch { }
}
}

View file

@ -12,6 +12,7 @@ namespace Yavsc.Blogs.Controllers
using Yavsc.Server.Helpers;
using Yavsc.Abstract.Helpers;
using Yavsc.Server.Models.FileSystem;
using Microsoft.Extensions.Options;
[Authorize,Route(APIPrefix + "/fs")]
public partial class FileSystemApiController : Controller
@ -19,15 +20,18 @@ namespace Yavsc.Blogs.Controllers
readonly ApplicationDbContext dbContext;
private readonly IAuthorizationService AuthorizationService;
private readonly ILogger _logger;
private readonly SiteSettings siteSettings;
public FileSystemApiController(ApplicationDbContext context,
IAuthorizationService authorizationService,
ILoggerFactory loggerFactory)
ILoggerFactory loggerFactory,
IOptions<SiteSettings> siteSettings)
{
AuthorizationService = authorizationService;
dbContext = context;
_logger = loggerFactory.CreateLogger<FileSystemApiController>();
this.siteSettings = siteSettings.Value;
}
[HttpGet()]
@ -41,7 +45,7 @@ namespace Yavsc.Blogs.Controllers
{
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
// _logger.LogInformation($"listing files from {User.Identity.Name}{subdir}");
var files = AbstractFileSystemHelpers.GetUserFiles(User.GetUserId(), subdir);
var files = FileSystemHelpers.GetUserFiles(siteSettings, User.GetUserId(), subdir);
return Ok(files);
}
@ -53,7 +57,7 @@ namespace Yavsc.Blogs.Controllers
List<FileReceivedInfo> received = new List<FileReceivedInfo>();
InvalidPathException pathex = null;
try {
destDir = User.EnsureDestinationDirectory(subdir);
destDir = User.EnsureDestinationDirectory(subdir, siteSettings);
} catch (InvalidPathException ex) {
pathex = ex;
}
@ -108,7 +112,7 @@ namespace Yavsc.Blogs.Controllers
var user = dbContext.Users.Single(
u => u.Id == uid
);
var info = user.MoveUserFileToDir(query.Id, query.To);
var info = user.MoveUserFileToDir(query.Id, query.To, siteSettings);
if (!info.Done) return new BadRequestObjectResult(info);
return Ok(new { moved = query.Id });
}
@ -131,11 +135,11 @@ namespace Yavsc.Blogs.Controllers
try {
if (Config.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.Id)).Exists)
{
var result = user.MoveUserFile(query.Id, query.To);
var result = user.MoveUserFile(query.Id, query.To, siteSettings);
if (!result.Done) return new BadRequestObjectResult(result);
}
else {
var result = user.MoveUserDir(query.Id, query.To);
var result = user.MoveUserDir(query.Id, query.To, siteSettings);
if (!result.Done) return new BadRequestObjectResult(result);
}
}
@ -161,7 +165,7 @@ namespace Yavsc.Blogs.Controllers
);
try {
var result = user.DeleteUserDirOrFile(id);
var result = user.DeleteUserDirOrFile(id, siteSettings);
if (!result.Done)
return new BadRequestObjectResult(result);
}

View file

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.SignalR;
using Yavsc.Server.Helpers;
using static Yavsc.Constants;
using Yavsc.Server.Hubs;
using Microsoft.Extensions.Options;
namespace Yavsc.Blogs.Controllers
{
@ -21,13 +22,20 @@ namespace Yavsc.Blogs.Controllers
private readonly IHubContext<ChatHub> hubContext;
readonly ApplicationDbContext dbContext;
public FileSystemStreamController(ApplicationDbContext context, ILiveProcessor liveProcessor, ILoggerFactory loggerFactory,
IHubContext<ChatHub> hubContext)
private readonly SiteSettings siteSettings;
public FileSystemStreamController(
ApplicationDbContext context,
ILiveProcessor liveProcessor,
ILoggerFactory loggerFactory,
IHubContext<ChatHub> hubContext,
IOptions<SiteSettings> siteSettings)
{
this.dbContext = context;
this.logger = loggerFactory.CreateLogger<FileSystemStreamController>();
this.liveProcessor = liveProcessor;
this.hubContext = hubContext;
this.siteSettings = siteSettings.Value;
}
[Authorize, Route("put/{filename}")]
@ -55,7 +63,7 @@ namespace Yavsc.Blogs.Controllers
);
string destDir = HttpContext.User.EnsureDestinationDirectory(filePath);
string destDir = HttpContext.User.EnsureDestinationDirectory(filePath, siteSettings);
logger.LogInformation($"Saving flow to {destDir}");
var userId = User.GetUserId();
var user = await dbContext.Users.FirstAsync(u => u.Id == userId);

View file

@ -8,7 +8,8 @@
"CorsAllowedOrigins": [
"https://localhost:5005",
"https://api.pschneider.fr"
]
],
"Blog": "blog"
},
"ConnectionStrings": {
"YavscConnection": "Server=localhost;Port=5432;Database=lame-db-name;Username=lame-user-name;Password=lame-password;"

View file

@ -18,6 +18,7 @@ namespace Yavsc.Org.Tests;
public class EstimateSignatureFileHelperTests : IDisposable
{
private readonly string _tempRoot;
private SiteSettings siteSettings;
public EstimateSignatureFileHelperTests()
{
@ -28,7 +29,7 @@ public class EstimateSignatureFileHelperTests : IDisposable
Path.GetTempPath(),
"yavsc-sig-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_tempRoot);
AbstractFileSystemHelpers.UserFilesDirName = _tempRoot;
this.siteSettings = new SiteSettings { Blog = _tempRoot };
}
public void Dispose()
@ -71,7 +72,7 @@ public class EstimateSignatureFileHelperTests : IDisposable
};
// Act
var fi = Run(user, 123L, SignatureType.Pro, payload);
var fi = Run(user, 123L, SignatureType.Pro, payload, this.siteSettings);
// Assert: file exists, sits under the user's root, and
// parses as a yavsc.signature/v1 envelope.
@ -98,7 +99,8 @@ public class EstimateSignatureFileHelperTests : IDisposable
var ct = TestContext.Current.CancellationToken;
await Assert.ThrowsAsync<ArgumentNullException>(() =>
EstimateSignatureFileHelper.ReceiveEstimateSignatureAsync(
user, 1L, SignatureType.Pro, payload: null!, token: ct));
user, 1L, SignatureType.Pro, payload: null!,
siteSettings, token: ct));
}
[Fact]
@ -109,19 +111,19 @@ public class EstimateSignatureFileHelperTests : IDisposable
var ct = TestContext.Current.CancellationToken;
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
EstimateSignatureFileHelper.ReceiveEstimateSignatureAsync(
user, 0L, SignatureType.Pro, payload, token: ct));
user, 0L, SignatureType.Pro, payload, this.siteSettings, token: ct));
}
// --- helpers ----------------------------------------------------
private static FileReceivedInfo Run(
ClaimsPrincipal user, long estimateId, SignatureType type, SignaturePadPayload payload)
ClaimsPrincipal user, long estimateId, SignatureType type, SignaturePadPayload payload, SiteSettings siteSettings)
{
// The helper is async; tests that don't care about the
// result can call it sync via .GetAwaiter().GetResult()
// because we know it never throws in the happy path.
return EstimateSignatureFileHelper
.ReceiveEstimateSignatureAsync(user, estimateId, type, payload, CancellationToken.None)
.ReceiveEstimateSignatureAsync(user, estimateId, type, payload, siteSettings, CancellationToken.None)
.GetAwaiter().GetResult();
}

View file

@ -490,14 +490,17 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
if (result.Succeeded)
{
_logger.LogInformation(3, "User created a new account with password.");
await _emailSender.SendEmailAsync(Config.SiteSetup.Owner.Name, Config.SiteSetup.Owner.EMail,
$"[{_siteSettings.Title}] Inscription avec mot de passe: {user.UserName} ", $"{user.Id}/{user.UserName}/{user.Email}");
await _emailSender.SendEmailAsync(
_siteSettings.Owner.Name,
_siteSettings.Owner.EMail,
$"[{_siteSettings.Title}] Inscription avec mot de passe: {user.UserName} ",
$"{user.Id}/{user.UserName}/{user.Email}");
// TODO user.DiskQuota = Startup.SiteSetup.UserFiles.Quota;
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
Uri authority = new Uri(Config.Authority);
Uri authority = new Uri(_siteSettings.Authority);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account",
@ -703,10 +706,15 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
await _signInManager.SignInAsync(user, isPersistent: false);
await _emailSender.SendEmailAsync(Config.SiteSetup.Owner.Name, Config.SiteSetup.Owner.EMail,
$"[{_siteSettings.Title}] Inscription via {info.LoginProvider}: {user.UserName} ", $"{user.Id}/{user.UserName}/{user.Email}");
await _emailSender.SendEmailAsync(
_siteSettings.Owner.Name,
_siteSettings.Owner.EMail,
$"[{_siteSettings.Title}] Inscription via {info.LoginProvider}: {user.UserName} ",
$"{user.Id}/{user.UserName}/{user.Email}");
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
_logger.LogInformation(6,
"User created an account using {Name} provider.",
info.LoginProvider);
return Redirect(returnUrl);
}

View file

@ -8,6 +8,7 @@ namespace Yavsc.Controllers
using Helpers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Models;
using ViewModels.FrontOffice;
using Yavsc.Server.Helpers;
@ -20,18 +21,21 @@ namespace Yavsc.Controllers
readonly ILogger _logger;
readonly IStringLocalizer _SR;
private readonly IBillingService _billing;
private readonly SiteSettings _siteSettings;
public FrontOfficeController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
IBillingService billing,
ILoggerFactory loggerFactory,
IStringLocalizer<FrontOfficeController> SR)
IStringLocalizer<FrontOfficeController> SR,
IOptions<SiteSettings> siteSettings)
{
_context = context;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<FrontOfficeController>();
_SR = SR;
_billing = billing;
_siteSettings = siteSettings.Value;
}
public ActionResult Index()
{
@ -95,8 +99,8 @@ namespace Yavsc.Controllers
[HttpGet]
public IActionResult EstimatePdf(long id)
{
ViewBag.TempDir = Config.SiteSetup.TempDir;
ViewBag.BillsDir = AbstractFileSystemHelpers.UserBillsDirName;
ViewBag.TempDir = _siteSettings.TempDir;
ViewBag.BillsDir = _siteSettings.Bills;
var estimate = _context.Estimates.Include(x => x.Query)
.Include(x => x.Query.Client)
.Include(x => x.Query.PerformerProfile)

View file

@ -1,20 +1,25 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
namespace Yavsc.Org.Controllers
{
public class FileSystemController : Controller
{
public FileSystemController()
private SiteSettings _siteSettings;
public FileSystemController(IOptions<SiteSettings> siteSettings)
{
_siteSettings = siteSettings.Value;
}
// Removed redundant empty constructor block
public IActionResult Index(string subdir="")
{
if (subdir !=null)
if (!subdir.IsValidYavscPath())
return new BadRequestResult();
var files = AbstractFileSystemHelpers.GetUserFiles(User.GetUserId(), subdir);
var files = FileSystemHelpers.GetUserFiles(_siteSettings, User.GetUserId(), subdir);
return View(files);
}
}

View file

@ -1044,7 +1044,7 @@ public static class HostingExtensions
Startup.Configure(app, siteSettings, smtpSettings,
payPalSettings, googleAuthSettings, localization, loggerFactory,
app.Environment.EnvironmentName);
app.ConfigureFileServerApp();
app.ConfigureFileServerApp(siteSettings.Value);
app.UseSession();
return app;
}
@ -1238,24 +1238,24 @@ ADD COLUMN IF NOT EXISTS ""Moderated"" boolean NOT NULL DEFAULT FALSE;");
#nullable disable
public static IApplicationBuilder ConfigureFileServerApp(this IApplicationBuilder app,
SiteSettings settings,
bool enableDirectoryBrowsing = false)
{
var userFilesDirInfo = new DirectoryInfo(Config.SiteSetup.Blog);
AbstractFileSystemHelpers.UserFilesDirName = userFilesDirInfo.FullName;
var userFilesDirInfo = new DirectoryInfo(settings.Blog);
if (!userFilesDirInfo.Exists) userFilesDirInfo.Create();
Config.UserFilesOptions = new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(AbstractFileSystemHelpers.UserFilesDirName),
FileProvider = new PhysicalFileProvider(userFilesDirInfo.FullName),
RequestPath = PathString.FromUriComponent(Constants.UserFilesPath),
EnableDirectoryBrowsing = enableDirectoryBrowsing,
};
Config.UserFilesOptions.EnableDefaultFiles = true;
Config.UserFilesOptions.StaticFileOptions.ServeUnknownFileTypes = true;
var avatarsDirInfo = new DirectoryInfo(Config.SiteSetup.Avatars);
var avatarsDirInfo = new DirectoryInfo(settings.Avatars);
if (!avatarsDirInfo.Exists) avatarsDirInfo.Create();
Config.AvatarsDirName = avatarsDirInfo.FullName;
@ -1267,7 +1267,7 @@ ADD COLUMN IF NOT EXISTS ""Moderated"" boolean NOT NULL DEFAULT FALSE;");
};
var gitdirinfo = new DirectoryInfo(Config.SiteSetup.GitRepository);
var gitdirinfo = new DirectoryInfo(settings.GitRepository);
Config.GitDirName = gitdirinfo.FullName;
if (!gitdirinfo.Exists) gitdirinfo.Create();
Config.GitOptions = new FileServerOptions()

View file

@ -115,11 +115,11 @@ namespace Yavsc.Helpers
return new TeXString(string.Join(lineSeparator,texlines));
}
public static bool GenerateEstimatePdf(this PdfGenerationViewModel Model)
public static bool GenerateEstimatePdf(this SiteSettings settings, PdfGenerationViewModel Model)
{
string errorMsg = null;
var billdir = Model.DestDir;
var tempdir = Config.SiteSetup.TempDir;
var tempdir = settings.TempDir;
string name = Model.BaseFileName;
string fullname = new FileInfo(
System.IO.Path.Combine(tempdir, name)).FullName;

View file

@ -2,6 +2,8 @@ using System.Diagnostics;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc;
using Yavsc.Blogspot;
using Yavsc.Models;
using Yavsc.Models.Access;
@ -18,14 +20,17 @@ public class OldBlogSpotService
private readonly ApplicationDbContext _context;
private readonly IAuthorizationService _authorizationService;
private readonly IFileSystemAuthManager fileSystemAuthManager;
private readonly SiteSettings siteSettings;
public OldBlogSpotService(ApplicationDbContext context,
IAuthorizationService authorizationService,
IFileSystemAuthManager fileSystemAuthManager)
IFileSystemAuthManager fileSystemAuthManager,
IOptions<SiteSettings> siteSettings)
{
_authorizationService = authorizationService;
_context = context;
this.fileSystemAuthManager = fileSystemAuthManager;
this.siteSettings = siteSettings.Value;
}
public Yavsc.Models.Blog.BlogPost Create(string userId, Yavsc.Models.Blog.BlogPost post, IFormFileCollection files)
@ -45,7 +50,7 @@ public class OldBlogSpotService
// Créer un répertoire pour les fichiers du blog
string blogFilesSubdir = $"blogs/{post.Id}";
string destDir = Path.Combine(
AbstractFileSystemHelpers.UserFilesDirName,
siteSettings.Blog,
user.UserName,
blogFilesSubdir
);

View file

@ -21,13 +21,10 @@ public class Startup
{
Config.GoogleSettings = googleSettings.Value;
ResourcesHelpers.GlobalLocalizer = localizer;
Config.SiteSetup = siteSettings.Value;
Config.SmtpSetup = smtpSettings.Value;
Config.Authority = siteSettings.Value.Authority;
string blogsDir = siteSettings.Value.Blog ?? throw new Exception("blogsDir is not set.");
string billsDir = siteSettings.Value.Bills ?? throw new Exception("billsDir is not set.");
AbstractFileSystemHelpers.UserFilesDirName = new DirectoryInfo(blogsDir).FullName;
AbstractFileSystemHelpers.UserBillsDirName = new DirectoryInfo(billsDir).FullName;
Config.Temp = siteSettings.Value.TempDir;
Config.PayPalSettings = payPalSettings.Value;
@ -35,7 +32,7 @@ public class Startup
// TODO implement an installation & upgrade procedure
// Create required directories
foreach (string dir in new string[] { AbstractFileSystemHelpers.UserFilesDirName, AbstractFileSystemHelpers.UserBillsDirName, Config.Temp })
foreach (string dir in new string[] { blogsDir, billsDir, Config.Temp })
{
if (dir == null)
{
@ -48,27 +45,27 @@ public class Startup
di.Create();
}
}
CheckApp(loggerFactory.CreateLogger<Startup>(), environmentName);
CheckApp(siteSettings.Value, loggerFactory.CreateLogger<Startup>(), environmentName);
}
public static void CheckApp(ILogger logger, string environmentName)
public static void CheckApp(SiteSettings settings, ILogger logger, string environmentName)
{
var appData = Environment.GetEnvironmentVariable("APPDATA");
if (appData == null)
{
logger.LogWarning("AppData was not found in environment variables");
if (Config.SiteSetup.DataDir == null) {
Config.SiteSetup.DataDir = "AppData"+environmentName;
logger.LogInformation("Using: "+Config.SiteSetup.DataDir);
} else logger.LogInformation("Using value from settings: "+Config.SiteSetup.DataDir);
DirectoryInfo di = new DirectoryInfo(Config.SiteSetup.DataDir);
if (settings.DataDir == null) {
settings.DataDir = "AppData"+environmentName;
logger.LogInformation("Using: "+settings.DataDir);
} else logger.LogInformation("Using value from settings: "+settings.DataDir);
DirectoryInfo di = new DirectoryInfo(settings.DataDir);
if (!di.Exists)
{
di.Create();
logger.LogWarning("Created dir : "+di.FullName);
}
logger.LogInformation("Using existing directory: "+di.FullName);
Environment.SetEnvironmentVariable("APPDATA", Config.SiteSetup.DataDir);
Environment.SetEnvironmentVariable("APPDATA", settings.DataDir);
logger.LogWarning("It has been set to : "+Environment.GetEnvironmentVariable("APPDATA"));
}

View file

@ -8,7 +8,7 @@ using Yavsc.ViewModels;
using Yavsc.ViewModels.Gen;
using Yavsc.Services;
using Microsoft.EntityFrameworkCore;
using Yavsc.Server.Helpers;
using Microsoft.Extensions.Options;
namespace Yavsc.ViewComponents
{
@ -17,20 +17,29 @@ namespace Yavsc.ViewComponents
readonly ApplicationDbContext dbContext;
readonly IBillingService billing;
readonly IStringLocalizer<BillViewComponent> localizer;
private readonly SiteSettings siteSettings;
public BillViewComponent(ApplicationDbContext dbContext,
IStringLocalizer<BillViewComponent> localizer,
IBillingService billing)
IBillingService billing,
IOptions<SiteSettings> siteSettings)
{
this.billing = billing;
this.dbContext = dbContext;
this.localizer = localizer;
this.siteSettings = siteSettings.Value;
}
public async Task<IViewComponentResult> InvokeAsync(string code, IBillable billable, OutputFormat format, bool asBill)
public async Task<IViewComponentResult> InvokeAsync(
string code,
IBillable billable,
OutputFormat format,
bool asBill,
SiteSettings settings
)
{
var di = new DirectoryInfo(Config.SiteSetup.Bills);
var dia = new DirectoryInfo(Config.SiteSetup.Avatars);
var di = new DirectoryInfo(settings.Bills);
var dia = new DirectoryInfo(settings.Avatars);
ViewBag.BillsDir = di.FullName;
ViewBag.AvatarsDir = dia.FullName;
ViewBag.AsBill = asBill; // vrai pour une facture, sinon, c'est un devis
@ -56,9 +65,9 @@ namespace Yavsc.ViewComponents
ViewBag.PerformerProfile = profile;
ViewBag.ActivityLabel = (await dbContext.Activities.SingleAsync(a => a.Code == billable.ActivityCode)).Name;
var proaddr = profile.OrganizationAddress.Address;
ViewBag.PerformerOrganizationAddress = proaddr.SplitAddressToTeX() ;
ViewBag.FooterPerformerOrganizationAddress = proaddr.SplitAddressToTeX(", ");
var proAddr = profile.OrganizationAddress.Address;
ViewBag.PerformerOrganizationAddress = proAddr.SplitAddressToTeX() ;
ViewBag.FooterPerformerOrganizationAddress = proAddr.SplitAddressToTeX(", ");
ViewBag.PerformerAddress = performer.PostalAddress?.Address.SplitAddressToTeX() ;
switch (format) {
@ -76,20 +85,21 @@ namespace Yavsc.ViewComponents
}
ViewComponentContext.ViewContext.Writer = oldWriter;
var genrtrData = new PdfGenerationViewModel
var pdfGenerationViewModel = new PdfGenerationViewModel
{
Temp = Config.Temp,
TeXSource = tex,
DestDir = AbstractFileSystemHelpers.UserBillsDirName,
DestDir = settings.Blog,
BaseFileName = billable.GetFileBaseName(billing)
};
if (genrtrData.GenerateEstimatePdf()) {
return this.View(new { Generated = genrtrData.BaseFileName+".pdf" });
if (settings.GenerateEstimatePdf(pdfGenerationViewModel)) {
return this.View(new { Generated = pdfGenerationViewModel.BaseFileName+".pdf" });
} else {
return View(new { Error = genrtrData.GenerationErrorMessage } );
return View(new { Error = pdfGenerationViewModel.GenerationErrorMessage } );
}
}
ViewBag.BillFileInfo = billable.GetBillInfo(billing);
ViewBag.BillFileInfo = billable.GetBillInfo(billing, siteSettings);
ViewBag.Settings = settings;
return View("Default",billable);
}

View file

@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels.UserFiles;
@ -11,24 +12,24 @@ namespace Yavsc.ViewComponents
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public DirectoryViewComponent(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
private readonly SiteSettings siteSettings;
public DirectoryViewComponent(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IOptions<SiteSettings> siteSettings)
{
_userManager = userManager;
_signInManager = signInManager;
this.siteSettings = siteSettings.Value;
}
public async Task<IViewComponentResult> InvokeAsync(string dirname)
{
string uid = ViewContext.HttpContext.User.GetUserId();
IViewComponentResult result = null;
result = View(new UserDirectoryInfo(
AbstractFileSystemHelpers.UserFilesDirName,
return View(new UserDirectoryInfo(
siteSettings.Blog,
uid, dirname));
return result;
}
}
}

View file

@ -7,7 +7,7 @@
@model Yavsc.ViewModels.Gen.PdfGenerationViewModel
@{
Model.GenerateEstimatePdf();
ViewBag.Settings.GenerateEstimatePdf(Model);
}
@if (Model.Generated) {
<div>

View file

@ -7,7 +7,7 @@
@model Yavsc.ViewModels.Gen.PdfGenerationViewModel
@{
Model.GenerateEstimatePdf();
SiteSettings.Value.GenerateEstimatePdf(Model);
}
@if (Model.Generated) {
<div>

View file

@ -1,10 +1,10 @@
<nav class="navbar navbar-expand-sm navbar-dark bg-dark" aria-label="Yavsc"
style="background-image: url('@Config.SiteSetup.Banner');
style="background-image: url('@SiteSettings.Value.Banner');
background-position: 0%;
background-attachment: fixed;">
<a class="navbar-brand" href="/">
<img src="~/images/yavsc-logo.svg" alt="Yavsc" style="height:32px; margin-right:8px; display:inline-block; vertical-align:middle;" />
@Config.SiteSetup.Title
@SiteSettings.Value.Title
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbar" aria-controls="navbar"

View file

@ -32,7 +32,6 @@ public static class Config
public static IConfigurationRoot? GoogleWebClientConfiguration { get; set; }
public static GoogleServiceAccount? GServiceAccount { get; set; }
public static SiteSettings SiteSetup { get; set; } = new SiteSettings();
public static FileServerOptions? UserFilesOptions { get; set; }
public static FileServerOptions? GitOptions { get; set; }
public static string AvatarsDirName { set; get; } = "Avatars";

View file

@ -21,11 +21,12 @@ namespace Yavsc.Helpers
return bill;
}
public static FileInfo GetBillInfo(this IBillable bill, IBillingService service)
public static FileInfo GetBillInfo(this IBillable bill,
IBillingService service, SiteSettings siteSettings)
{
var suffix = bill.GetIsAcquitted() ? "-ack":null;
var filename = bill.GetFileBaseName(service)+".pdf";
return new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
return new FileInfo(Path.Combine(siteSettings.Bills, filename));
}
}
}

View file

@ -64,6 +64,7 @@ public static class EstimateSignatureFileHelper
long estimateId,
SignatureType type,
SignaturePadPayload payload,
SiteSettings siteSettings,
CancellationToken token = default)
{
if (user is null) throw new ArgumentNullException(nameof(user));
@ -77,7 +78,7 @@ public static class EstimateSignatureFileHelper
// (not user-derived), so we skip the IsValidYavscPath
// check that ReceiveUserFile performs on user-supplied
// subpaths.
var root = user.EnsureDestinationDirectory(SignaturesSubdir);
var root = user.EnsureDestinationDirectory(SignaturesSubdir, siteSettings);
var fileName = FileNameFormat(type, estimateId, DateTime.UtcNow.Ticks);
var fullPath = Path.Combine(root, fileName);

View file

@ -13,6 +13,7 @@ using Yavsc.Exceptions;
using Yavsc.Abstract.Helpers;
using ImageMagick;
using Yavsc.Server.Models.FileSystem;
using Yavsc.ViewModels.UserFiles;
namespace Yavsc.Server.Helpers
{
public static class FileSystemHelpers
@ -27,10 +28,12 @@ namespace Yavsc.Server.Helpers
}
}
}
public static async Task<FileReceivedInfo> ReceiveProSignatureAsync(this ClaimsPrincipal user, string billingCode, long estimateId, IFormFile formFile, string signType)
public static async Task<FileReceivedInfo> ReceiveProSignatureAsync(this ClaimsPrincipal user, string billingCode, long estimateId, IFormFile formFile, string signType,
SiteSettings settings
)
{
var item = new FileReceivedInfo(
Config.SiteSetup.Bills,
settings.Bills,
AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, estimateId));
var fi = new FileInfo(item.FullName);
@ -39,16 +42,11 @@ namespace Yavsc.Server.Helpers
return item;
}
public static string GetAvatarUri(this ApplicationUser user)
{
return $"/{Config.SiteSetup.Avatars}/{user.UserName}.png";
}
public static string EnsureDestinationDirectory(
this ClaimsPrincipal user,
string subpath)
string subpath, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.Identity.Name);
var root = Path.Combine(siteSettings.Blog, user.Identity.Name);
if (!string.IsNullOrWhiteSpace(subpath))
{
if (!subpath.IsValidYavscPath())
@ -69,18 +67,18 @@ namespace Yavsc.Server.Helpers
/// <param name="user"></param>
/// <param name="fileName"></param>
public static void DeleteUserFile(this ApplicationUser user, string fileName)
public static void DeleteUserFile(this ApplicationUser user, string fileName, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var root = Path.Combine(siteSettings.Blog, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileName));
if (!fi.Exists) return;
fi.Delete();
user.DiskUsage -= fi.Length;
}
public static FsOperationInfo DeleteUserDirOrFile(this ApplicationUser user, string dirName)
public static FsOperationInfo DeleteUserDirOrFile(this ApplicationUser user, string dirName, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var root = Path.Combine(siteSettings.Blog, user.UserName);
if (string.IsNullOrEmpty(dirName))
return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest, ErrorMessage = "specify a directory or file name" };
@ -101,9 +99,9 @@ namespace Yavsc.Server.Helpers
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserDir(this ApplicationUser user, string fromDirName, string toDirName)
public static FsOperationInfo MoveUserDir(this ApplicationUser user, string fromDirName, string toDirName, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var root = Path.Combine(siteSettings.Blog, user.UserName);
if (string.IsNullOrEmpty(fromDirName))
return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.InvalidRequest, ErrorMessage = "specify a dir name " };
@ -127,28 +125,28 @@ namespace Yavsc.Server.Helpers
di.MoveTo(destPath);
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserFileToDir(this ApplicationUser user, string fileNameFrom, string fileNameDest)
public static FsOperationInfo MoveUserFileToDir(this ApplicationUser user, string fileNameFrom, string fileNameDest, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var root = Path.Combine(siteSettings.Blog, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileNameFrom));
if (!fi.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" };
if (!fi.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" };
string dest;
if (!string.IsNullOrEmpty(fileNameDest)) dest = Path.Combine(root, fileNameDest);
else dest = root;
var fo = new FileInfo(dest);
if (fo.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.DestExists, ErrorMessage = "destination file name is an existing file" };
if (fo.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.DestExists, ErrorMessage = "destination file name is an existing file" };
var dout = new DirectoryInfo(dest);
if (!dout.Exists) dout.Create();
fi.MoveTo(Path.Combine(dout.FullName, fi.Name));
return new FsOperationInfo { Done = true };
}
public static FsOperationInfo MoveUserFile(this ApplicationUser user, string fileNameFrom, string fileNameDest)
public static FsOperationInfo MoveUserFile(this ApplicationUser user, string fileNameFrom, string fileNameDest, SiteSettings siteSettings)
{
var root = Path.Combine(AbstractFileSystemHelpers.UserFilesDirName, user.UserName);
var root = Path.Combine(siteSettings.Blog, user.UserName);
var fi = new FileInfo(Path.Combine(root, fileNameFrom));
if (!fi.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" };
if (!fi.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.NotFound, ErrorMessage = "no file to move" };
var fo = new FileInfo(Path.Combine(root, fileNameDest));
if (fo.Exists) return new FsOperationInfo { ErrorCode = ErrorCode.DestExists, ErrorMessage = "destination file name is an existing file" };
if (fo.Exists) return new FsOperationInfo { Done = false, ErrorCode = ErrorCode.DestExists, ErrorMessage = "destination file name is an existing file" };
fi.MoveTo(fo.FullName);
return new FsOperationInfo { Done = true };
}
@ -245,7 +243,9 @@ namespace Yavsc.Server.Helpers
}
public static FileReceivedInfo ReceiveAvatar(this ApplicationUser user, IFormFile formFile)
public static FileReceivedInfo ReceiveAvatar(this ApplicationUser user,
IFormFile formFile,
SiteSettings settings)
{
if (user == null) throw new ArgumentNullException(nameof(user));
if (formFile == null) throw new ArgumentNullException(nameof(formFile));
@ -256,7 +256,7 @@ namespace Yavsc.Server.Helpers
avatarsRequestPath = Constants.AvatarsPath;
}
var avatarsDirectory = Config.SiteSetup?.Avatars;
var avatarsDirectory = settings.Avatars;
if (string.IsNullOrWhiteSpace(avatarsDirectory))
{
avatarsDirectory = "avatars";
@ -306,5 +306,12 @@ namespace Yavsc.Server.Helpers
return $"{basename}-{flow.SequenceNumber}{ext}";
}
public static UserDirectoryInfo GetUserFiles(SiteSettings settings, string userId, string subdir)
{
UserDirectoryInfo di = new UserDirectoryInfo(settings.Blog, userId, subdir);
return di;
}
}
}

View file

@ -5,6 +5,8 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc;
using Yavsc.Blogspot;
using Yavsc.Models;
using Yavsc.Models.Access;
@ -19,15 +21,18 @@ public class BlogSpotService
private readonly ApplicationDbContext _context;
private readonly IAuthorizationService _authorizationService;
private readonly IFileSystemAuthManager fileSystemAuthManager;
private readonly SiteSettings siteSettings;
public BlogSpotService(
ApplicationDbContext context,
IAuthorizationService authorizationService,
IFileSystemAuthManager fileSystemAuthManager)
IFileSystemAuthManager fileSystemAuthManager,
IOptions<SiteSettings> siteSettings)
{
_authorizationService = authorizationService;
_context = context;
this.fileSystemAuthManager = fileSystemAuthManager;
this.siteSettings = siteSettings.Value;
}
public BlogPost Create(string userId, BlogPost post, IFormFileCollection files)
@ -42,13 +47,14 @@ public class BlogSpotService
if (files != null && files.Count > 0)
{
var user = _context.Users.FirstOrDefault(u => u.Id == userId);
if (user != null)
{
if (user == null)
throw new InvalidOperationException($"Utilisateur {userId} non trouvé.");
try
{
string blogFilesSubdir = $"blogs/{post.Id}";
string destDir = Path.Combine(
AbstractFileSystemHelpers.UserFilesDirName,
siteSettings.Blog,
user.UserName,
blogFilesSubdir);
var di = new DirectoryInfo(destDir);
@ -83,7 +89,6 @@ public class BlogSpotService
Debug.WriteLine($"Erreur lors du traitement des fichiers : {ex.Message}");
}
}
}
return post;
}
@ -202,7 +207,7 @@ public class BlogSpotService
{
string blogFilesSubdir = $"blogs/{blog.Id}";
string destDir = Path.Combine(
AbstractFileSystemHelpers.UserFilesDirName,
siteSettings.Blog,
userEntity.UserName,
blogFilesSubdir);
var di = new DirectoryInfo(destDir);

View file

@ -6,89 +6,72 @@ namespace Yavsc
{
public class SiteSettings
{
public string Title { get; set; } = "Yavsc";
public string Title { get; set; }
public string Slogan { get; set; } = "";
public string Banner { get; set; } = "";
public string Slogan { get; set; }
public string Banner { get; set; }
public string StyleSheet { get; set; } = "site.css";
public string FavIcon { get; set; } = "favicon.ico";
public string Logo { get; set; } = "logo.png";
public string StyleSheet { get; set; }
public string FavIcon { get; set; }
public string Logo { get; set; }
/// <summary>
/// Origins to allow via the CORS "default" policy.
/// Each entry must be a full origin (scheme + host [+ port]), e.g. "https://app.example.com".
/// </summary>
public IList<string> CorsAllowedOrigins { get; set; } = new List<string>
{
"https://localhost:5001"
};
public IList<string> CorsAllowedOrigins { get; set; }
/// <summary>
/// External Url
/// </summary>
/// <value></value>
public string ExternalUrl { get; set; } = "http://lua.pschneider.fr";
public string ExternalUrl { get; set; }
/// <summary>
/// Base URL of the API fronting this site.
/// </summary>
public string ApiUrl { get; set; } = "";
public string ApiUrl { get; set; }
/// <summary>
/// Must be a fqdn.
/// </summary>
/// <returns></returns>
public string Authority { get; set; } = "lua.pschneider.fr";
public string Authority { get; set; }
/// <summary>
/// Owner's email
/// </summary>
/// <returns></returns>
public StaticContact Owner { get; set; } = new StaticContact
{
EMail = "root@lua.pschneider.fr",
Name = "Root"
} ;
public StaticContact Owner { get; set; }
/// <summary>
/// Administrator's email
/// </summary>
/// <returns></returns>
public StaticContact Admin { get; set; } = new StaticContact
{
EMail = "root@lua.pschneider.fr",
Name = "Root"
} ;
public StaticContact Admin { get; set; }
public string DataDir { get; set; } = "data";
public string Avatars { get; set; } = "avatars";
public string DataDir { get; set; }
public string Avatars { get; set; }
public long Quota { get; set; }
public string Blog { get; set; } = "blogs";
public string Bills { get; set; } = "bills";
public string GitRepository { get; set; } = "sources";
public string Blog { get; set; }
public string Bills { get; set; }
public string GitRepository { get; set; }
public string BusinessName { get; set; } = "Yavsc";
public string? Street { get; set; }
public string? PostalCode { get; set; }
public string? CountryCode { get; set; }
public string HomeViewName { get; set; } = "Home";
/// <summary>
/// Specifies the directory where should be
/// generated pdf files using pandoc
/// </summary>
/// <returns>The temporary directory to use</returns>
public string TempDir { get; set; } = "temp";
public string TempDir { get; set; }
/// <summary>
/// Disk usage user list maximum length in memory
/// </summary>
/// <value></value>
public int DUUserListLen { get; set; } = 256;
public int DUUserListLen { get; set; }
/// <summary>
/// Default acl file name
/// </summary>
/// <value></value>
public string AccessListFileName { get; set; } = ".access";
public string AccessListFileName { get; set; }
}
}