Add OBS podcast ingestion and account withdrawal privacy controls
Support scoped RTMPS publishing through MediaMTX, authenticated replay, resource accounting and PostIt activation/revocation. Close withdrawn accounts, erase managed files and purge eligible payment residues after one year. Include migrations, documentation and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
97b350be2d
commit
b157dce4e4
54 changed files with 12996 additions and 50 deletions
72
src/Yavsc.Server/Helpers/PaymentResidueService.cs
Normal file
72
src/Yavsc.Server/Helpers/PaymentResidueService.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Abstract.Administration;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Server.Helpers;
|
||||
|
||||
public interface IPaymentResidueService
|
||||
{
|
||||
Task<PaymentResiduePurgeResult> PurgeAsync(CancellationToken ct);
|
||||
Task<DateTimeOffset?> GetNextExpiryAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PaymentResidueService(ApplicationDbContext db, TimeProvider clock,
|
||||
ILogger<PaymentResidueService> logger) : IPaymentResidueService
|
||||
{
|
||||
private IQueryable<ApplicationUser> AccountsWithResidues()
|
||||
=> db.Users.AsNoTracking().Where(u => u.WithdrawnAt != null
|
||||
&& (db.ResourceSubscriptions.Any(s => s.UserId == u.Id)
|
||||
|| db.PayPalPayment.Any(p => p.ExecutorId == u.Id)
|
||||
|| db.PerformerDonations.Any(d => d.DonorId == u.Id || d.PerformerId == u.Id)));
|
||||
|
||||
public async Task<DateTimeOffset?> GetNextExpiryAsync(CancellationToken ct)
|
||||
{
|
||||
var dates = await AccountsWithResidues().Select(u => u.WithdrawnAt).ToListAsync(ct);
|
||||
return dates.Select(d => d?.AddYears(1)).Min();
|
||||
}
|
||||
|
||||
public async Task<PaymentResiduePurgeResult> PurgeAsync(CancellationToken ct)
|
||||
{
|
||||
var now = clock.GetUtcNow();
|
||||
var candidates = await AccountsWithResidues()
|
||||
.Select(u => new { u.Id, u.WithdrawnAt }).ToListAsync(ct);
|
||||
var ids = candidates.Where(u => u.WithdrawnAt!.Value.AddYears(1) <= now).Select(u => u.Id);
|
||||
var users = 0;
|
||||
var subscriptions = 0;
|
||||
var payments = 0;
|
||||
var donations = 0;
|
||||
var legacyPayments = 0;
|
||||
foreach (var id in ids)
|
||||
{
|
||||
var count = await ResourceUsageTracker.WithUserLockAsync(db, id, async () =>
|
||||
{
|
||||
var owner = await db.Users.AsNoTracking().SingleAsync(u => u.Id == id, ct);
|
||||
if (owner.WithdrawnAt is null || owner.WithdrawnAt.Value.AddYears(1) > now)
|
||||
throw new InvalidOperationException("Withdrawal retention deadline changed during purge.");
|
||||
var rows = await db.ResourceSubscriptions.Where(s => s.UserId == id).ToListAsync(ct);
|
||||
var rowIds = rows.Select(s => s.Id).ToArray();
|
||||
var receipts = await db.ResourceSubscriptionPayments.Where(p => rowIds.Contains(p.SubscriptionId)).ToListAsync(ct);
|
||||
var donationRows = await db.PerformerDonations.Where(p => p.DonorId == id || p.PerformerId == id).ToListAsync(ct);
|
||||
var legacy = await db.PayPalPayment.Include(p => p.Links).Where(p => p.ExecutorId == id).ToListAsync(ct);
|
||||
foreach (var payment in legacy)
|
||||
if (payment.Links is not null) db.HyperLink.RemoveRange(payment.Links);
|
||||
db.PerformerDonations.RemoveRange(donationRows);
|
||||
db.PayPalPayment.RemoveRange(legacy);
|
||||
db.ResourceSubscriptionPayments.RemoveRange(receipts);
|
||||
await db.SaveChangesAsync(ct);
|
||||
db.ResourceSubscriptions.RemoveRange(rows);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return (Subscriptions: rows.Count, Payments: receipts.Count, Donations: donationRows.Count, LegacyPayments: legacy.Count);
|
||||
}, ct);
|
||||
if (count.Subscriptions != 0 || count.Payments != 0 || count.Donations != 0 || count.LegacyPayments != 0) users++;
|
||||
subscriptions += count.Subscriptions;
|
||||
payments += count.Payments;
|
||||
donations += count.Donations;
|
||||
legacyPayments += count.LegacyPayments;
|
||||
}
|
||||
logger.LogInformation("Purged payment residues: {Users} withdrawn accounts, {Subscriptions} subscriptions, {Payments} receipts, {Donations} donations, {LegacyPayments} legacy payments",
|
||||
users, subscriptions, payments, donations, legacyPayments);
|
||||
return new(users, subscriptions, payments, donations, legacyPayments);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +1,50 @@
|
|||
#nullable enable
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Server.Helpers;
|
||||
|
||||
public sealed class ResourceUsageLimitException() : InvalidOperationException("Le seuil de consommation est atteint.")
|
||||
{
|
||||
}
|
||||
|
||||
public static class ResourceUsageTracker
|
||||
{
|
||||
private static readonly SemaphoreSlim LocalGate = new(1, 1);
|
||||
|
||||
public static Task RecordStorageAsync(ApplicationDbContext db, string userId, string userName,
|
||||
string path, long bytes, CancellationToken cancellationToken = default)
|
||||
string path, long bytes, CancellationToken cancellationToken = default,
|
||||
Func<Task>? write = null, ResourceUsageOptions? policy = null, decimal bandwidthMb = 0m)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(userId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(bytes);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(bandwidthMb);
|
||||
return WithUserLockAsync(db, userId, async () =>
|
||||
{
|
||||
if (await IsWithdrawingAsync(db, userId, cancellationToken))
|
||||
throw new InvalidOperationException("Storage accounting is closed for this withdrawn account.");
|
||||
var stored = await db.ResourceStorageRecords.FindAsync([userId, path], cancellationToken);
|
||||
if (stored is not null) await db.Entry(stored).ReloadAsync(cancellationToken);
|
||||
var delta = bytes - (stored?.Bytes ?? 0L);
|
||||
if (write is not null)
|
||||
{
|
||||
if (policy is null && (delta > 0 || bandwidthMb > 0m))
|
||||
throw new ArgumentException("Storage admission requires a resource policy.", nameof(policy));
|
||||
if (policy is not null && await UpdateCoreAsync(db, userId, userName, 0m, 0, 0m, bandwidthMb, userId,
|
||||
Constants.ResourceUsageDefaultCurrency, policy, Math.Max(0L, delta), cancellationToken) is null)
|
||||
{
|
||||
db.GetService<ILoggerFactory>().CreateLogger("ResourceUsageTracker")
|
||||
.LogWarning("Storage admission refused at resource threshold for {UserId}", userId);
|
||||
throw new ResourceUsageLimitException();
|
||||
}
|
||||
await write();
|
||||
}
|
||||
|
||||
if (stored is null && bytes > 0)
|
||||
db.ResourceStorageRecords.Add(new ResourceStorageRecord { UserId = userId, Path = path, Bytes = bytes });
|
||||
else if (stored is not null)
|
||||
|
|
@ -100,6 +124,7 @@ public static class ResourceUsageTracker
|
|||
decimal bandwidthMb, string? actorUserId, string currency, ResourceUsageOptions? policy,
|
||||
long anticipatedStorageBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await IsWithdrawingAsync(dbContext, userId, cancellationToken)) return null;
|
||||
var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId;
|
||||
var now = DateTime.UtcNow;
|
||||
var storageMb = (decimal)storageBytes / (1024m * 1024m);
|
||||
|
|
@ -151,6 +176,15 @@ public static class ResourceUsageTracker
|
|||
return record;
|
||||
}
|
||||
|
||||
private static async Task<bool> IsWithdrawingAsync(ApplicationDbContext db, string userId, CancellationToken ct)
|
||||
{
|
||||
if (!await db.Users.AsNoTracking().AnyAsync(u => u.Id == userId && u.WithdrawalRequestedAt != null, ct))
|
||||
return false;
|
||||
db.GetService<ILoggerFactory>().CreateLogger("ResourceUsageTracker")
|
||||
.LogWarning("Refused resource accounting for withdrawn account {UserId}", userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static async Task<T> WithUserLockAsync<T>(ApplicationDbContext dbContext, string userId,
|
||||
Func<Task<T>> action, CancellationToken cancellationToken)
|
||||
{
|
||||
|
|
|
|||
24
src/Yavsc.Server/Helpers/WithdrawnAccountMiddleware.cs
Normal file
24
src/Yavsc.Server/Helpers/WithdrawnAccountMiddleware.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Server.Helpers;
|
||||
|
||||
public sealed class WithdrawnAccountMiddleware(RequestDelegate next)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context, ApplicationDbContext db)
|
||||
{
|
||||
var id = context.User.GetUserId();
|
||||
if (!string.IsNullOrWhiteSpace(id) && await db.Users.AsNoTracking()
|
||||
.AnyAsync(u => u.Id == id && u.WithdrawalRequestedAt != null, context.RequestAborted))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
await context.Response.WriteAsJsonAsync(new Microsoft.AspNetCore.Mvc.ProblemDetails
|
||||
{
|
||||
Status = 401, Title = "Compte ferme", Detail = "Ce compte fait l'objet d'un retrait et ne peut plus etre utilise."
|
||||
}, context.RequestAborted);
|
||||
return;
|
||||
}
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
|
|
@ -146,7 +146,8 @@ namespace Yavsc.Models
|
|||
builder.Entity<ApplicationUser>().Property(u => u.Avatar).HasDefaultValue(Constants.DefaultAvatar);
|
||||
builder.Entity<ApplicationUser>().Property(u => u.DiskQuota).HasDefaultValue(Constants.DefaultFSQ);
|
||||
builder.Entity<ResourceStorageRecord>().HasKey(r => new { r.UserId, r.Path });
|
||||
builder.Entity<ApplicationUser>().HasAlternateKey(u => u.Email);
|
||||
builder.Entity<ApplicationUser>().Property(u => u.Email).IsRequired();
|
||||
builder.Entity<ApplicationUser>().HasIndex(u => u.Email).IsUnique();
|
||||
builder.Entity<BlackListed>().HasOne<ApplicationUser>(bl => bl.User);
|
||||
builder.Entity<BlackListed>().HasOne<ApplicationUser>(bl => bl.Owner);
|
||||
builder.Entity<UserActivity>().HasKey(u => new { u.DoesCode, u.UserId });
|
||||
|
|
|
|||
|
|
@ -95,6 +95,10 @@ namespace Yavsc.Models
|
|||
|
||||
public long DiskQuota { get; set; } = Constants.DefaultFSQ;
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public DateTimeOffset? WithdrawalRequestedAt { get; set; }
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public DateTimeOffset? WithdrawnAt { get; set; }
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public DateTimeOffset? PremiumDiskQuotaUntil { get; set; }
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public DateTimeOffset? DiscoveryDiskQuotaUntil { get; set; }
|
||||
|
|
|
|||
|
|
@ -15,6 +15,14 @@ namespace Yavsc.Models.Streaming
|
|||
public DateTimeOffset? PreparedAt { get; set; }
|
||||
public DateTimeOffset? StartedAt { get; set; }
|
||||
public bool PodcastDeleted { get; set; }
|
||||
[MaxLength(64), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public string? ObsKeyHash { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public DateTimeOffset? ObsEnabledUntil { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public Guid? ObsConnectionId { get; set; }
|
||||
[MaxLength(512), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public string? ObsLastError { get; set; }
|
||||
|
||||
[Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
[Display(Name="FlowIdLabel", ResourceType=typeof(LiveFlow))]
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ namespace Yavsc.Services
|
|||
var subjectId = GetSubjectId(context.Subject);
|
||||
if (subjectId == null) return;
|
||||
var user = await _userManager.FindByIdAsync(subjectId);
|
||||
if (user == null) return;
|
||||
if (user == null || user.WithdrawalRequestedAt is not null) return;
|
||||
context.IssuedClaims = await GetClaimsFromUserAsync(context, user);
|
||||
}
|
||||
|
||||
|
|
@ -87,7 +87,7 @@ namespace Yavsc.Services
|
|||
return;
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(subjectId);
|
||||
context.IsActive = user != null;
|
||||
context.IsActive = user != null && user.WithdrawalRequestedAt is null;
|
||||
}
|
||||
|
||||
private static string? GetSubjectId(ClaimsPrincipal claimsPrincipal)
|
||||
|
|
|
|||
Loading…
Reference in a new issue