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
|
|
@ -1049,10 +1049,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
return View(new UnregisterViewModel { UserId = id, ReturnUrl = returnUrl });
|
||||
}
|
||||
|
||||
[HttpPost, Authorize("AdministratorOnly")]
|
||||
public async Task<IActionResult> AdminDelete(UnregisterViewModel model)
|
||||
[HttpPost, Authorize("AdministratorOnly"), ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> AdminDelete(UnregisterViewModel model,
|
||||
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
var result = await DeleteUser(model.UserId);
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var result = await DeleteUser(model.UserId, withdrawal);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
|
|
@ -1062,14 +1064,16 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
return View();
|
||||
}
|
||||
|
||||
[HttpPost, Authorize]
|
||||
public async Task<IActionResult> Delete(UnregisterViewModel model)
|
||||
[HttpPost, Authorize, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Delete(UnregisterViewModel model,
|
||||
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var result = await DeleteUser(model.UserId);
|
||||
if (model.UserId != User.GetUserId()) return Forbid();
|
||||
var result = await DeleteUser(User.GetUserId(), withdrawal);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
|
|
@ -1080,20 +1084,30 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
|
||||
return RedirectToAction("Index", "Home");
|
||||
}
|
||||
async Task<IdentityResult> DeleteUser(string userId)
|
||||
async Task<IdentityResult> DeleteUser(string userId, Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
ApplicationUser user = await _userManager.FindByIdAsync(userId);
|
||||
|
||||
_dbContext.DeviceDeclaration.RemoveRange(_dbContext.DeviceDeclaration.Where(g => g.DeviceOwnerId == userId));
|
||||
|
||||
return await _userManager.DeleteAsync(user);
|
||||
try
|
||||
{
|
||||
await withdrawal.WithdrawAsync(userId, HttpContext.RequestAborted);
|
||||
return IdentityResult.Success;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or HttpRequestException
|
||||
or Yavsc.Web.Services.SubscriptionOperationException or DbUpdateException or InvalidOperationException)
|
||||
{
|
||||
_logger.LogError(ex, "Account withdrawal failed for {UserId}", userId);
|
||||
return IdentityResult.Failed(new IdentityError
|
||||
{
|
||||
Code = "WithdrawalFailed",
|
||||
Description = "Le retrait n'a pas pu etre termine. Contactez l'administration pour reprendre l'effacement."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, _localizer[error.Code]);
|
||||
ModelState.AddModelError(string.Empty, error.Code == "WithdrawalFailed" ? error.Description : _localizer[error.Code]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -96,6 +96,10 @@ public static class HostingExtensions
|
|||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
services.AddScoped<Yavsc.Web.Services.IResourceSubscriptionService, Yavsc.Web.Services.ResourceSubscriptionService>();
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.AddScoped<IPaymentResidueService, PaymentResidueService>();
|
||||
services.AddScoped<Yavsc.Web.Services.IAccountWithdrawalService, Yavsc.Web.Services.AccountWithdrawalService>();
|
||||
services.Configure<Yavsc.Services.PodcastOptions>(builder.Configuration.GetSection("Podcast"));
|
||||
services.AddHostedService<Yavsc.Web.Services.PaymentResiduePurgeWorker>();
|
||||
|
||||
services.AddSession();
|
||||
|
||||
|
|
@ -1067,6 +1071,7 @@ public static class HostingExtensions
|
|||
app.UseSwaggerUI();
|
||||
app.UseRouting();
|
||||
app.UseAuthentication();
|
||||
app.UseMiddleware<WithdrawnAccountMiddleware>();
|
||||
app.UseIdentityServer();
|
||||
app.UseAuthorization();
|
||||
app.UseCors("default");
|
||||
|
|
|
|||
5228
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs
generated
Normal file
5228
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
43
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs
Normal file
43
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AccountWithdrawal : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers");
|
||||
migrationBuilder.CreateIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers", column: "Email", unique: true);
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "WithdrawalRequestedAt",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "WithdrawnAt",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers");
|
||||
migrationBuilder.AddUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers", column: "Email");
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WithdrawalRequestedAt",
|
||||
table: "AspNetUsers");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WithdrawnAt",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5242
src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs
generated
Normal file
5242
src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,61 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PodcastObsIngestion : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "ObsConnectionId",
|
||||
table: "LiveFlow",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "ObsEnabledUntil",
|
||||
table: "LiveFlow",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "ObsKeyHash",
|
||||
table: "LiveFlow",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "ObsLastError",
|
||||
table: "LiveFlow",
|
||||
type: "character varying(512)",
|
||||
maxLength: 512,
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ObsConnectionId",
|
||||
table: "LiveFlow");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ObsEnabledUntil",
|
||||
table: "LiveFlow");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ObsKeyHash",
|
||||
table: "LiveFlow");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ObsLastError",
|
||||
table: "LiveFlow");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1218,9 +1218,16 @@ namespace Yavsc.Migrations
|
|||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<DateTimeOffset?>("WithdrawalRequestedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset?>("WithdrawnAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasAlternateKey("Email");
|
||||
b.HasIndex("Email")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
|
@ -3200,6 +3207,20 @@ namespace Yavsc.Migrations
|
|||
b.Property<string>("MediaType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid?>("ObsConnectionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset?>("ObsEnabledUntil")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("ObsKeyHash")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("ObsLastError")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("OwnerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
|
|
|||
208
src/Yavsc.Org/Services/AccountWithdrawalService.cs
Normal file
208
src/Yavsc.Org/Services/AccountWithdrawalService.cs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
#nullable enable
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.Web.Services;
|
||||
|
||||
public interface IAccountWithdrawalService
|
||||
{
|
||||
Task WithdrawAsync(string userId, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class AccountWithdrawalService(ApplicationDbContext db, UserManager<ApplicationUser> users,
|
||||
IPayPalSubscriptionGateway paypal, IOptions<SiteSettings> site, IOptions<PodcastOptions> podcasts,
|
||||
TimeProvider clock, ILogger<AccountWithdrawalService> logger) : IAccountWithdrawalService
|
||||
{
|
||||
public async Task WithdrawAsync(string userId, CancellationToken ct)
|
||||
{
|
||||
var user = await users.FindByIdAsync(userId)
|
||||
?? throw new SubscriptionOperationException(404, "Compte introuvable.");
|
||||
if (user.WithdrawnAt is not null) return;
|
||||
var userName = user.UserName ?? throw new InvalidOperationException("Withdrawal requires a storage owner name.");
|
||||
var personalDirectory = Child(site.Value.UserFilesRoot, userName);
|
||||
var avatarFiles = new[] { ".png", ".s.png", ".xs.png" }.Select(ext => Child(site.Value.Avatars, userName + ext)).ToArray();
|
||||
var started = await ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
|
||||
{
|
||||
await db.Entry(user).ReloadAsync(ct);
|
||||
if (user.WithdrawnAt is not null) return false;
|
||||
user.WithdrawalRequestedAt ??= clock.GetUtcNow();
|
||||
user.LockoutEnabled = true;
|
||||
user.LockoutEnd = DateTimeOffset.MaxValue;
|
||||
user.SecurityStamp = Guid.NewGuid().ToString();
|
||||
await db.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}, ct);
|
||||
if (!started) return;
|
||||
|
||||
var subscriptions = await db.ResourceSubscriptions.Where(s => s.UserId == userId).ToListAsync(ct);
|
||||
foreach (var subscription in subscriptions)
|
||||
{
|
||||
if (subscription.State is "CANCELLED" or "EXPIRED") continue;
|
||||
if (subscription.PayPalId is null)
|
||||
{
|
||||
if (subscription.State == "CREATING")
|
||||
throw new SubscriptionOperationException(409, "Une creation PayPal doit etre rapprochee avant de confirmer le retrait.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var remote = await paypal.GetAsync(subscription.PayPalId, ct);
|
||||
if (remote.State is not ("CANCELLED" or "EXPIRED"))
|
||||
await paypal.CancelAsync(subscription.PayPalId, ct);
|
||||
}
|
||||
subscription.State = "CANCELLED";
|
||||
subscription.NextBillingAt = null;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
DeleteDirectory(personalDirectory);
|
||||
foreach (var path in avatarFiles)
|
||||
{
|
||||
RejectLink(path);
|
||||
if (Directory.Exists(Path.GetDirectoryName(path))) File.Delete(path);
|
||||
}
|
||||
await DeletePodcastsAsync(userId, ct);
|
||||
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
|
||||
{
|
||||
await db.Entry(user).ReloadAsync(ct);
|
||||
if (user.WithdrawnAt is not null) return true;
|
||||
db.DeviceDeclaration.RemoveRange(await db.DeviceDeclaration.Where(d => d.DeviceOwnerId == userId).ToListAsync(ct));
|
||||
db.UserLogins.RemoveRange(await db.UserLogins.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.UserTokens.RemoveRange(await db.UserTokens.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.UserClaims.RemoveRange(await db.UserClaims.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.UserRoles.RemoveRange(await db.UserRoles.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.BankIdentity.RemoveRange(await db.BankIdentity.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.Contact.RemoveRange(await db.Contact.Where(d => d.OwnerId == userId || d.UserId == userId).ToListAsync(ct));
|
||||
db.ResourceUsageRecords.RemoveRange(await db.ResourceUsageRecords.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
db.ResourceStorageRecords.RemoveRange(await db.ResourceStorageRecords.Where(d => d.UserId == userId).ToListAsync(ct));
|
||||
var posts = await db.BlogSpot.Where(p => p.AuthorId == userId).ToListAsync(ct);
|
||||
foreach (var post in posts)
|
||||
{
|
||||
post.Title = "Contenu retire";
|
||||
post.Article = null;
|
||||
post.Photo = null;
|
||||
}
|
||||
var comments = await db.Comment.Where(p => p.AuthorId == userId).ToListAsync(ct);
|
||||
foreach (var comment in comments) comment.Article = "Contenu retire";
|
||||
var performer = await db.Performers.SingleOrDefaultAsync(p => p.PerformerId == userId, ct);
|
||||
if (performer is not null)
|
||||
{
|
||||
performer.Active = false;
|
||||
performer.AcceptNotifications = false;
|
||||
performer.AcceptPublicContact = false;
|
||||
performer.UseGeoLocalizationToReduceDistanceWithClients = false;
|
||||
performer.WebSite = "";
|
||||
performer.DonationPayPalEmail = null;
|
||||
}
|
||||
var flows = await db.LiveFlow.Where(f => f.OwnerId == userId).ToListAsync(ct);
|
||||
foreach (var flow in flows)
|
||||
{
|
||||
flow.Title = "Contenu retire";
|
||||
flow.Pitch = "";
|
||||
flow.PublicAnnouncement = "";
|
||||
flow.DifferedFileName = "";
|
||||
flow.PodcastDeleted = true;
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsConnectionId = null;
|
||||
flow.ObsLastError = null;
|
||||
}
|
||||
var fileIds = await db.UploadedFiles.Where(f => f.OwnerId == userId
|
||||
|| db.BlogAttachedFiles.Any(a => a.FileId == f.Id && a.Post.AuthorId == userId))
|
||||
.Select(f => f.Id).ToListAsync(ct);
|
||||
var files = await db.UploadedFiles.Where(f => fileIds.Contains(f.Id)).ToListAsync(ct);
|
||||
foreach (var file in files)
|
||||
{
|
||||
file.Path = "";
|
||||
file.Length = 0;
|
||||
file.ContentType = "application/octet-stream";
|
||||
}
|
||||
user.UserName = "withdrawn-" + Guid.NewGuid().ToString("N");
|
||||
user.NormalizedUserName = user.UserName.ToUpperInvariant();
|
||||
user.Email = user.UserName + "@invalid.invalid";
|
||||
user.NormalizedEmail = user.Email.ToUpperInvariant();
|
||||
user.EmailConfirmed = false;
|
||||
user.FullName = null;
|
||||
user.PhoneNumber = null;
|
||||
user.PhoneNumberConfirmed = false;
|
||||
user.PasswordHash = null;
|
||||
user.TwoFactorEnabled = false;
|
||||
user.PostalAddressId = null;
|
||||
user.DedicatedGoogleCalendar = null;
|
||||
user.Avatar = Constants.DefaultAvatar;
|
||||
user.AllowMonthlyEmail = false;
|
||||
user.DiskUsage = 0;
|
||||
user.PremiumDiskQuotaUntil = null;
|
||||
user.DiscoveryDiskQuotaUntil = null;
|
||||
user.WithdrawnAt = clock.GetUtcNow();
|
||||
await db.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}, ct);
|
||||
logger.LogInformation("Account withdrawal completed, files erased and identity pseudonymized");
|
||||
}
|
||||
|
||||
private async Task DeletePodcastsAsync(string userId, CancellationToken ct)
|
||||
{
|
||||
var root = Path.GetFullPath(podcasts.Value.RootPath);
|
||||
if (!Directory.Exists(root)) return;
|
||||
RejectLink(root);
|
||||
foreach (var directory in Directory.EnumerateDirectories(root))
|
||||
{
|
||||
if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out _)) continue;
|
||||
RejectLink(directory);
|
||||
var index = Path.Combine(directory, "index.json");
|
||||
RejectLink(index);
|
||||
if (!File.Exists(index)) continue;
|
||||
await using var stream = File.OpenRead(index);
|
||||
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: ct);
|
||||
var podcast = document.RootElement.GetProperty("Manifest").GetProperty("Podcast");
|
||||
var owner = podcast.GetProperty("OwnerId").GetString();
|
||||
if (owner == userId)
|
||||
{
|
||||
if (podcast.TryGetProperty("State", out var state) && state.GetString() == "Live"
|
||||
|| podcast.TryGetProperty("Replay", out var replay) && replay.ValueKind == JsonValueKind.Object
|
||||
&& replay.TryGetProperty("State", out var replayState) && replayState.GetString() == "Processing")
|
||||
throw new SubscriptionOperationException(409, "Un podcast est encore en direct ou en cours de conversion ; attendre son arret avant de reprendre le retrait.");
|
||||
await stream.DisposeAsync();
|
||||
DeleteDirectory(directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string Child(string root, string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root) || string.IsNullOrWhiteSpace(name) || name != Path.GetFileName(name)
|
||||
|| name is "." or ".." || name.Contains('\\'))
|
||||
throw new InvalidOperationException("Invalid withdrawal storage configuration or user path.");
|
||||
var fullRoot = Path.GetFullPath(root);
|
||||
RejectLink(fullRoot);
|
||||
var child = Path.GetFullPath(Path.Combine(fullRoot, name));
|
||||
if (!child.StartsWith(fullRoot.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("Withdrawal path escapes its storage root.");
|
||||
return child;
|
||||
}
|
||||
|
||||
private static void RejectLink(string path)
|
||||
{
|
||||
if ((File.Exists(path) || Directory.Exists(path)) && File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint))
|
||||
throw new IOException("Withdrawal refuses symbolic links in managed storage.");
|
||||
}
|
||||
|
||||
private static void DeleteDirectory(string path)
|
||||
{
|
||||
if (!Directory.Exists(path)) return;
|
||||
RejectLink(path);
|
||||
foreach (var entry in Directory.EnumerateFileSystemEntries(path))
|
||||
{
|
||||
RejectLink(entry);
|
||||
if (Directory.Exists(entry)) DeleteDirectory(entry);
|
||||
else File.Delete(entry);
|
||||
}
|
||||
Directory.Delete(path);
|
||||
}
|
||||
}
|
||||
38
src/Yavsc.Org/Services/PaymentResiduePurgeWorker.cs
Normal file
38
src/Yavsc.Org/Services/PaymentResiduePurgeWorker.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
using Yavsc.Server.Helpers;
|
||||
|
||||
namespace Yavsc.Web.Services;
|
||||
|
||||
public sealed class PaymentResiduePurgeWorker(IServiceScopeFactory scopes,
|
||||
ILogger<PaymentResiduePurgeWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var delay = TimeSpan.FromMinutes(1);
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var residues = scope.ServiceProvider.GetRequiredService<IPaymentResidueService>();
|
||||
await residues.PurgeAsync(stoppingToken);
|
||||
var clock = scope.ServiceProvider.GetRequiredService<TimeProvider>();
|
||||
var now = clock.GetUtcNow();
|
||||
var expiry = await residues.GetNextExpiryAsync(stoppingToken);
|
||||
if (expiry is not null)
|
||||
{
|
||||
var until = expiry.Value - now;
|
||||
if (until < delay) delay = until > TimeSpan.Zero ? until : TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Automatic payment residue purge failed; retrying in one minute");
|
||||
}
|
||||
await Task.Delay(delay, stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -38,6 +38,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
|
|||
throw new SubscriptionOperationException(400, "Pack inconnu.");
|
||||
return ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
|
||||
{
|
||||
await RequireActiveAccountAsync(userId, ct);
|
||||
var existing = await db.ResourceSubscriptions.Where(s => s.UserId == userId
|
||||
&& s.State != "CANCELLED" && s.State != "EXPIRED").SingleOrDefaultAsync(ct);
|
||||
if (existing is not null)
|
||||
|
|
@ -69,6 +70,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
|
|||
public Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct)
|
||||
=> ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
|
||||
{
|
||||
await RequireActiveAccountAsync(subscription.UserId, ct, allowPendingWithdrawal: true);
|
||||
await db.Entry(subscription).ReloadAsync(ct);
|
||||
CheckBinding(subscription, remote);
|
||||
subscription.PayPalId = remote.Id;
|
||||
|
|
@ -87,6 +89,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
|
|||
var transactions = await paypal.TransactionsAsync(remote.Id, subscription.CreatedAt, clock.GetUtcNow(), ct);
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
|
||||
{
|
||||
await RequireActiveAccountAsync(subscription.UserId, ct);
|
||||
await db.Entry(subscription).ReloadAsync(ct);
|
||||
CheckBinding(subscription, remote);
|
||||
subscription.State = remote.State;
|
||||
|
|
@ -174,4 +177,11 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
|
|||
|| remote.State is not ("APPROVAL_PENDING" or "APPROVED" or "ACTIVE" or "SUSPENDED" or "CANCELLED" or "EXPIRED"))
|
||||
throw new SubscriptionOperationException(409, "L'abonnement PayPal ne correspond pas au compte et au pack attendus.");
|
||||
}
|
||||
|
||||
private async Task RequireActiveAccountAsync(string userId, CancellationToken ct, bool allowPendingWithdrawal = false)
|
||||
{
|
||||
if (await db.Users.AnyAsync(u => u.Id == userId &&
|
||||
(u.WithdrawnAt != null || !allowPendingWithdrawal && u.WithdrawalRequestedAt != null), ct))
|
||||
throw new SubscriptionOperationException(409, "Le compte est retire ; aucun nouveau credit ne peut etre attribue.");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,13 @@
|
|||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<p>
|
||||
Cette action est <strong>immédiate et irréversible</strong>. Toutes les données
|
||||
associées à votre compte seront supprimées, et vous serez déconnecté.
|
||||
Cette action ferme définitivement votre compte et vous déconnecte. Le retrait est confirmé
|
||||
après résiliation des abonnements et suppression de vos fichiers personnels, avatars et podcasts.
|
||||
Vos identifiants sont effacés ou pseudonymisés. En cas d'erreur, le compte est bloqué et
|
||||
l'administration doit reprendre l'effacement ; aucun retrait réussi n'est annoncé.
|
||||
Les données techniques de paiement restent conservées jusqu'à un an après le retrait effectif.
|
||||
Les pièces comptables relèvent d'une conservation légale distincte.
|
||||
Consultez la <a asp-controller="Home" asp-action="Privacy">politique de confidentialité</a>.
|
||||
</p>
|
||||
|
||||
<form asp-controller="Account" asp-action="Delete" method="post" class="form-horizontal" role="form">
|
||||
|
|
|
|||
|
|
@ -1,16 +1,120 @@
|
|||
@{
|
||||
ViewBag.Title = Localizer["Home"];
|
||||
ViewBag.Title = "Confidentialité et protection des données";
|
||||
}
|
||||
|
||||
<markdown>
|
||||
# La confidentialité
|
||||
# Confidentialité et protection des données
|
||||
|
||||
À aucun moment, aucune adresse postale,
|
||||
aucune adresse e-mail ni aucun numéro de téléphone
|
||||
ne sont transmis à personne. Seul le système
|
||||
son [possesseur ou l'administration](/Home/Contact) ont accès
|
||||
à ces informations.
|
||||
Dernière mise à jour : 8 novembre 2026.
|
||||
|
||||
De plus, le droit de retrait est permanent
|
||||
et sa [mise en oeuvre est immédiate](/Account/Delete).
|
||||
## Responsable et contact
|
||||
|
||||
L'exploitant de Yavsc, identifié sur la [page de contact](/Home/Contact),
|
||||
est votre interlocuteur pour les traitements de données et l'exercice de vos droits.
|
||||
Cette politique concerne Yavsc et son client PostIt.
|
||||
|
||||
## Données et utilisation
|
||||
|
||||
Le service traite les identifiants du compte, coordonnées renseignées, préférences,
|
||||
contenus publiés, fichiers, échanges nécessaires aux prestations, données techniques
|
||||
de connexion et de consommation, et références des abonnements et paiements.
|
||||
Ces données servent à fournir le service, authentifier les utilisateurs, gérer les
|
||||
prestations et paiements, protéger la plateforme et comptabiliser les ressources.
|
||||
Le fonctionnement du service repose sur l'exécution du contrat ; la sécurité relève
|
||||
de l'intérêt légitime de l'exploitant et les obligations comptables de la loi.
|
||||
Les fonctions optionnelles fondées sur un consentement peuvent être désactivées.
|
||||
|
||||
## Accès et transmissions
|
||||
|
||||
La confidentialité ne signifie pas qu'aucune donnée n'est transmise :
|
||||
|
||||
* Le titulaire du compte et les administrateurs habilités accèdent aux informations
|
||||
nécessaires à leur rôle. L'accès administratif sert au support et à l'exploitation.
|
||||
* Les contenus publiés sont accessibles selon leur visibilité et leurs autorisations.
|
||||
Les parties à une demande, un devis ou une prestation peuvent recevoir les
|
||||
coordonnées et pièces nécessaires à cette relation ; elles ne sont pas réservées
|
||||
exclusivement à l'administration.
|
||||
* PostIt et les autres clients OAuth/OIDC autorisés reçoivent les informations prévues
|
||||
par leurs autorisations : identifiant, nom de compte, adresse e-mail et rôles
|
||||
lorsque l'accès au profil leur est accordé.
|
||||
* Lors d'un appel direct avec PostIt, l'adresse réseau que vous acceptez de communiquer
|
||||
et les paramètres de connexion sont partagés avec l'interlocuteur pour établir
|
||||
la liaison. L'audio et, si activée, la vidéo sont transmis aux participants ;
|
||||
les diffusions de podcasts transmettent aussi les médias aux personnes autorisées.
|
||||
Pour une émission diffusée avec OBS ou un autre encodeur externe, le relais média
|
||||
configuré reçoit le flux, l'adresse réseau du diffuseur et une clé technique
|
||||
limitée à l'émission. Cette clé permet de diffuser, pas d'accéder aux données
|
||||
du compte ni de regarder les podcasts ; elle peut être révoquée dans PostIt.
|
||||
* Les prestataires d'hébergement et de messagerie traitent les données nécessaires
|
||||
au stockage, au fonctionnement et à l'acheminement des messages.
|
||||
* PayPal reçoit les informations nécessaires au paiement et à l'abonnement :
|
||||
formule, montant, devise, références et identifiant technique de rapprochement.
|
||||
Pour les dons, l'adresse PayPal du destinataire est aussi utilisée. Les données
|
||||
que vous fournissez directement à PayPal relèvent également de sa propre politique.
|
||||
Yavsc ne stocke pas votre numéro de carte bancaire pour ces abonnements.
|
||||
* Si vous choisissez une connexion externe, notamment Google, ce fournisseur
|
||||
intervient dans l'authentification. Les intégrations de calendrier et de notification,
|
||||
lorsqu'elles sont configurées et utilisées, transmettent les données nécessaires
|
||||
à leur fonction aux fournisseurs correspondants.
|
||||
* Si la modération par Claude est activée sur cette instance, le contenu soumis
|
||||
et son contexte sont transmis à Anthropic pour cette modération.
|
||||
* Des données peuvent être communiquées aux autorités lorsqu'une obligation légale
|
||||
l'impose. Leur publication ou transmission à d'autres utilisateurs dépend aussi
|
||||
des fonctions et autorisations que vous utilisez.
|
||||
|
||||
Certains fournisseurs peuvent traiter les données hors de l'Union européenne.
|
||||
L'exploitant doit vérifier les lieux de traitement et garanties contractuelles
|
||||
applicables aux fournisseurs effectivement activés ; leurs coordonnées et ces
|
||||
garanties peuvent être demandées via la page de contact.
|
||||
|
||||
## Retrait et fichiers
|
||||
|
||||
Vous pouvez [demander le retrait de votre compte](/Account/Delete).
|
||||
Le compte est bloqué dès le début du traitement. Le retrait effectif n'est confirmé
|
||||
qu'après arrêt des abonnements et effacement des fichiers personnels, avatars,
|
||||
pièces jointes personnelles/de blog et podcasts sur les volumes gérés par le service.
|
||||
Les contenus de profil et publications du compte sont effacés ou neutralisés,
|
||||
ses moyens de connexion sont supprimés et son identité est pseudonymisée.
|
||||
Une ligne technique peut rester nécessaire aux relations avec les documents conservés ;
|
||||
elle ne permet plus de se connecter.
|
||||
|
||||
Une erreur d'effacement ou de résiliation est signalée : le retrait n'est pas annoncé
|
||||
comme réussi et l'administration doit reprendre le traitement.
|
||||
La suppression sur le service ne supprime pas les copies téléchargées par d'autres
|
||||
personnes ni les données détenues indépendamment par les prestataires.
|
||||
|
||||
## Paiements et conservation
|
||||
|
||||
Par exception au retrait ordinaire, les données techniques PayPal, abonnements,
|
||||
mensualités et dons nécessaires au rapprochement restent conservées pendant
|
||||
au maximum **un an à compter du retrait effectif**. Cette limite ne repart pas à
|
||||
chaque paiement ou notification.
|
||||
|
||||
Les résidus arrivés à échéance sont purgés automatiquement ; une action réservée
|
||||
aux administrateurs dans PostIt permet également de lancer la purge des données
|
||||
éligibles. Les comptes actifs et les retraits non finalisés ne sont pas concernés.
|
||||
L'exploitant doit surveiller ce traitement et corriger tout incident ou arrêt
|
||||
du service empêchant la purge à échéance.
|
||||
|
||||
**Les factures, pièces comptables et informations nécessaires aux obligations légales
|
||||
ne relèvent pas de cette limite d'un an.** Elles sont conservées selon les délais
|
||||
légaux applicables, avec accès limité aux besoins comptables et légaux.
|
||||
Les sauvegardes et journaux d'exploitation font l'objet d'une politique distincte :
|
||||
leur durée et les mesures empêchant la réactivation de données retirées doivent
|
||||
être précisées par l'exploitant selon le déploiement réel.
|
||||
|
||||
## Cookies, stockage local et droits
|
||||
|
||||
Yavsc utilise des cookies nécessaires à la connexion, à la session et à la protection
|
||||
des formulaires. PostIt conserve localement les éléments nécessaires à sa session ;
|
||||
la déconnexion et l'effacement des données locales doivent aussi être réalisés sur
|
||||
les appareils que vous utilisez.
|
||||
|
||||
Vous pouvez demander l'accès, la rectification, l'effacement, la limitation,
|
||||
l'opposition et, lorsque applicable, la portabilité de vos données, ainsi que retirer
|
||||
un consentement sans affecter les traitements antérieurs. Contactez l'exploitant
|
||||
via la [page de contact](/Home/Contact). Vous pouvez également introduire une
|
||||
réclamation auprès de la [CNIL](https://www.cnil.fr/).
|
||||
|
||||
La [règle de consommation et les abonnements](/Home/CGU) sont décrits séparément.
|
||||
</markdown>
|
||||
|
|
|
|||
Loading…
Reference in a new issue