Dons PayPal

This commit is contained in:
Paul Schneider 2026-11-02 10:40:29 +00:00
commit e3b4414ab1
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
45 changed files with 7476 additions and 9 deletions

View file

@ -664,8 +664,13 @@ namespace Yavsc.Controllers
if (_dbContext.Performers.Any(p=>p.PerformerId == uid))
{
_dbContext.Update(model);
_dbContext.Entry(model).Property(p => p.DonationPayPalEmail).IsModified = false;
}
else
{
model.DonationPayPalEmail = null;
_dbContext.Performers.Add(model);
}
else _dbContext.Performers.Add(model);
_dbContext.SaveChanges(User.GetUserId());
// Give this user the Performer role
if (!User.IsInMsRole("Performer"))
@ -716,6 +721,8 @@ namespace Yavsc.Controllers
bool existing = _dbContext.Performers.Any(x => x.PerformerId == uid);
if (existing)
{
if (await _dbContext.PerformerDonations.AnyAsync(d => d.PerformerId == uid))
return Conflict("Ce profil a recu des dons et doit etre conserve pour leur suivi. Desactivez les nouveaux dons dans les parametres PayPal.");
_dbContext.Performers.Remove(
_dbContext.Performers.First(x => x.PerformerId == uid)
);

View file

@ -0,0 +1,232 @@
#nullable enable
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Models.Payment;
using Yavsc.Models.Workflow;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels.Podcast;
using Yavsc.Web.Services;
namespace Yavsc.Controllers;
[Authorize(Policy = "WebUser")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class DonationController(ApplicationDbContext db, IPayPalDonationGateway paypal,
IOptions<SiteSettings> siteOptions, ILogger<DonationController> logger) : Controller
{
[HttpGet]
public async Task<IActionResult> Index(CancellationToken ct)
=> View(await db.PerformerDonations.AsNoTracking().Where(d => d.DonorId == User.GetUserId())
.OrderByDescending(d => d.CreatedAt)
.Join(db.Users, d => d.PerformerId, u => u.Id,
(d, u) => new DonationDetailsViewModel(d, u.UserName ?? d.PerformerId)).ToArrayAsync(ct));
[HttpGet]
public async Task<IActionResult> Settings(CancellationToken ct)
{
var performer = await db.Performers.FindAsync([User.GetUserId()], ct);
if (performer == null)
{
Response.StatusCode = StatusCodes.Status404NotFound;
ViewData["PaymentError"] = "Creez d'abord votre profil performer dans Mon compte > Parametres professionnels pour recevoir des dons.";
return View("Error");
}
return View(new DonationSettingsViewModel { PayPalEmail = performer.DonationPayPalEmail });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Settings(DonationSettingsViewModel model, CancellationToken ct)
{
var performer = await db.Performers.FindAsync([User.GetUserId()], ct);
if (performer == null) return NotFound();
if (!ModelState.IsValid) return View(model);
performer.DonationPayPalEmail = string.IsNullOrWhiteSpace(model.PayPalEmail) ? null : model.PayPalEmail.Trim();
await db.SaveChangesAsync(ct);
TempData["DonationSettingsSaved"] = true;
return RedirectToAction(nameof(Settings));
}
[HttpGet]
public async Task<IActionResult> Create(string id, CancellationToken ct)
{
var performer = await RecipientAsync(id, ct);
if (performer == null) return NotFound();
return View(new CreateDonationViewModel { PerformerId = id, PerformerName = performer.Performer.UserName ?? id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateDonationViewModel model, CancellationToken ct)
{
var performer = await RecipientAsync(model.PerformerId, ct);
if (performer == null) return NotFound();
model.PerformerName = performer.Performer.UserName ?? performer.PerformerId;
if (decimal.Round(model.Amount, 2) != model.Amount)
ModelState.AddModelError(nameof(model.Amount), "Le montant doit avoir au maximum deux decimales.");
if (!ModelState.IsValid) return View(model);
var urls = PaymentUrls();
var donation = new PerformerDonation
{
Id = Guid.NewGuid(), DonorId = User.GetUserId(), PerformerId = performer.PerformerId,
RecipientEmail = performer.DonationPayPalEmail!, Amount = model.Amount, CreatedAt = DateTimeOffset.UtcNow
};
db.PerformerDonations.Add(donation);
await db.SaveChangesAsync(ct);
donation.CheckoutToken = await paypal.CreateAsync(donation,
urls.Return + donation.Id, urls.Cancel + donation.Id, urls.Notify, ct);
donation.State = PerformerDonationState.AwaitingApproval;
await SaveAsync(donation, ct);
return Redirect(paypal.CheckoutUrl(donation.CheckoutToken));
}
[HttpGet]
public async Task<IActionResult> Return(Guid id, string token, CancellationToken ct)
{
var donation = await OwnedAsync(id, ct);
if (donation == null || string.IsNullOrWhiteSpace(token) || donation.CheckoutToken != token) return NotFound();
if (donation.State == PerformerDonationState.AwaitingApproval)
await paypal.ApproveAsync(donation, ct);
return RedirectToAction(nameof(Details), new { id });
}
[HttpGet]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
var donation = await OwnedAsync(id, ct);
if (donation == null) return NotFound();
var name = await db.Users.Where(u => u.Id == donation.PerformerId).Select(u => u.UserName).SingleAsync(ct);
return View(new DonationDetailsViewModel(donation, name ?? donation.PerformerId));
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Confirm(Guid id, CancellationToken ct)
{
var donation = await OwnedAsync(id, ct);
if (donation == null) return NotFound();
if (donation.State == PerformerDonationState.Completed)
return RedirectToAction(nameof(Details), new { id });
if (donation.State != PerformerDonationState.AwaitingApproval)
throw new DonationPaymentException(409, "Ce paiement est deja traite ou en cours de verification. Ne creez pas un second don.");
var approval = await paypal.ApproveAsync(donation, ct);
donation.State = PerformerDonationState.Processing;
await SaveAsync(donation, ct);
var receipt = await paypal.CaptureAsync(donation, approval.PayerId, ct);
// An IPN may have confirmed the payment while the capture request was in flight.
await db.Entry(donation).ReloadAsync(ct);
if (donation.TransactionId != null && donation.TransactionId != receipt.TransactionId)
throw new DonationPaymentException(409, "La reference PayPal ne correspond pas au don.");
if (donation.State is PerformerDonationState.Processing or PerformerDonationState.Pending)
{
donation.TransactionId = receipt.TransactionId;
donation.State = receipt.Completed ? PerformerDonationState.Completed : PerformerDonationState.Pending;
donation.CompletedAt = receipt.Completed ? DateTimeOffset.UtcNow : null;
await SaveAsync(donation, ct);
}
return RedirectToAction(nameof(Details), new { id });
}
[HttpGet]
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
{
var donation = await OwnedAsync(id, ct);
if (donation == null) return NotFound();
return View(donation);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> CancelConfirm(Guid id, CancellationToken ct)
{
var donation = await OwnedAsync(id, ct);
if (donation == null) return NotFound();
if (donation.State == PerformerDonationState.AwaitingApproval)
{
donation.State = PerformerDonationState.Cancelled;
await SaveAsync(donation, ct);
}
return RedirectToAction(nameof(Details), new { id });
}
[AllowAnonymous, HttpPost, IgnoreAntiforgeryToken, RawPayPalNotification, RequestSizeLimit(64 * 1024)]
public async Task<IActionResult> Notify(CancellationToken ct)
{
using var reader = new StreamReader(Request.Body, Encoding.UTF8);
var body = await reader.ReadToEndAsync(ct);
var fields = await paypal.VerifyNotificationAsync(body, ct);
if (!Guid.TryParseExact(fields.GetValueOrDefault("invoice"), "N", out var id))
throw new DonationPaymentException(400, "Reference de don PayPal invalide.");
var donation = await db.PerformerDonations.FindAsync([id], ct);
if (donation == null) return NotFound();
var transactionId = fields.GetValueOrDefault("txn_id");
if (fields.GetValueOrDefault("txn_type") != "express_checkout"
|| !string.Equals(fields.GetValueOrDefault("receiver_email"), donation.RecipientEmail, StringComparison.OrdinalIgnoreCase)
|| !PayPalDonationGateway.SameAmount(fields.GetValueOrDefault("mc_gross"), donation.Amount)
|| fields.GetValueOrDefault("mc_currency") != donation.Currency
|| string.IsNullOrWhiteSpace(transactionId) || transactionId.Length > 32
|| (donation.TransactionId != null && donation.TransactionId != transactionId)
|| donation.State is PerformerDonationState.Created or PerformerDonationState.AwaitingApproval or PerformerDonationState.Cancelled)
throw new DonationPaymentException(409, "La notification PayPal ne correspond pas au don.");
var paymentState = fields.GetValueOrDefault("payment_status");
if (paymentState is not ("Completed" or "Pending" or "Denied" or "Failed" or "Expired" or "Voided"))
{
logger.LogWarning("PayPal donation {DonationId} notification has unsupported status {Status}", id, paymentState);
return Ok();
}
if (donation.State != PerformerDonationState.Completed)
{
donation.TransactionId = transactionId;
donation.State = paymentState switch
{
"Completed" => PerformerDonationState.Completed,
"Pending" => PerformerDonationState.Pending,
_ => PerformerDonationState.Failed
};
donation.CompletedAt = paymentState == "Completed" ? DateTimeOffset.UtcNow : null;
await SaveAsync(donation, ct);
}
return Ok();
}
private Task<PerformerProfile?> RecipientAsync(string id, CancellationToken ct)
=> db.Performers.Include(p => p.Performer).SingleOrDefaultAsync(p => p.PerformerId == id
&& p.Active && p.DonationPayPalEmail != null && p.DonationPayPalEmail != "", ct);
private Task<PerformerDonation?> OwnedAsync(Guid id, CancellationToken ct)
=> db.PerformerDonations.SingleOrDefaultAsync(d => d.Id == id && d.DonorId == User.GetUserId(), ct);
private async Task SaveAsync(PerformerDonation donation, CancellationToken ct)
{
donation.Revision = Guid.NewGuid();
await db.SaveChangesAsync(ct);
}
private (string Return, string Cancel, string Notify) PaymentUrls()
{
if (!Uri.TryCreate(siteOptions.Value.ExternalUrl, UriKind.Absolute, out var origin)
|| origin.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(origin.UserInfo))
throw new DonationPaymentException(503, "L'adresse HTTPS du site n'est pas configuree.");
var root = siteOptions.Value.ExternalUrl.TrimEnd('/') + "/";
return (root + "Donation/Return?id=", root + "Donation/Cancel?id=", root + "Donation/Notify");
}
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var executed = await next();
var error = executed.Exception;
if (error == null || error is not (DonationPaymentException or DbUpdateConcurrencyException) || Response.HasStarted)
return;
logger.LogError(error, "Donation request failed for {Action}", context.ActionDescriptor.DisplayName);
executed.ExceptionHandled = true;
Response.StatusCode = error is DonationPaymentException payment ? payment.StatusCode : 409;
ViewData["PaymentError"] = error is DonationPaymentException known
? known.Message : "Ce don a ete modifie par une autre requete. Consultez son etat avant de recommencer.";
if (context.ActionArguments.TryGetValue("id", out var id) && id is Guid donationId)
ViewData["DonationId"] = donationId;
executed.Result = View("Error");
}
}

View file

@ -0,0 +1,104 @@
#nullable enable
using System.Globalization;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Streaming;
using Yavsc.Services;
using Yavsc.Models;
using Yavsc.ViewModels.Podcast;
using Yavsc.Web.Services;
namespace Yavsc.Controllers;
[Authorize(Policy = "WebUser")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class PodcastController(
PodcastWebClient api,
ApplicationDbContext db,
ILogger<PodcastController> logger) : Controller
{
[HttpGet]
public async Task<IActionResult> Index(CancellationToken ct)
{
var podcasts = await api.GetAsync<List<PodcastResponse>>("", ct);
var ownerIds = podcasts.Select(p => p.OwnerId).Distinct().ToArray();
var performers = await db.Performers.AsNoTracking()
.Where(p => ownerIds.Contains(p.PerformerId) && p.Active && p.DonationPayPalEmail != null
&& p.DonationPayPalEmail != "")
.Select(p => p.PerformerId).ToArrayAsync(ct);
return View(new PodcastCatalogueViewModel(
podcasts.OrderByDescending(p => p.CreatedAt).ToArray(), performers.ToHashSet(StringComparer.Ordinal)));
}
[HttpGet("Podcast/{id:guid}/index.m3u8")]
public async Task<IActionResult> Playlist(Guid id, CancellationToken ct)
{
var manifest = await api.GetAsync<PodcastManifestResponse>(id.ToString(), ct);
var text = new StringBuilder("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:15\n")
.Append("#EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:EVENT\n");
foreach (var segment in manifest.Segments)
{
text.Append(CultureInfo.InvariantCulture, $"#EXTINF:{segment.DurationSeconds:0.######},\n");
text.Append(Url.Action(nameof(Segment), new { id, sequence = segment.Sequence })).Append('\n');
}
if (manifest.Podcast.State != PodcastState.Live) text.Append("#EXT-X-ENDLIST\n");
return Content(text.ToString(), "application/vnd.apple.mpegurl", Encoding.UTF8);
}
[HttpGet("Podcast/{id:guid}/segments/{sequence:int:min(0)}.ts")]
public Task<IActionResult> Segment(Guid id, int sequence, CancellationToken ct)
=> ProxyAsync($"{id}/segments/{sequence}.ts", "video/mp2t", ct);
[HttpGet("Podcast/{id:guid}/replay.mp4")]
[HttpHead("Podcast/{id:guid}/replay.mp4")]
public Task<IActionResult> Replay(Guid id, CancellationToken ct)
=> ProxyAsync($"{id}/replay.mp4", "video/mp4", ct);
private async Task<IActionResult> ProxyAsync(string path, string contentType, CancellationToken ct)
{
RangeHeaderValue? range = null;
if (Request.Headers.TryGetValue("Range", out var value)
&& !RangeHeaderValue.TryParse(value.ToString(), out range))
return BadRequest(new ProblemDetails { Status = 400, Title = "Plage de lecture invalide." });
using var response = await api.SendAsync(HttpMethods.IsHead(Request.Method)
? HttpMethod.Head : HttpMethod.Get, path, range, ct);
Response.StatusCode = (int)response.StatusCode;
Response.ContentType = contentType;
Response.Headers.CacheControl = "private, no-store";
Response.ContentLength = response.Content.Headers.ContentLength;
if (response.Content.Headers.ContentRange != null)
Response.Headers.ContentRange = response.Content.Headers.ContentRange.ToString();
if (response.Headers.AcceptRanges.Count > 0)
Response.Headers.AcceptRanges = string.Join(", ", response.Headers.AcceptRanges);
if (!HttpMethods.IsHead(Request.Method))
await response.Content.CopyToAsync(Response.Body, ct);
return new EmptyResult();
}
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var executed = await next();
var error = executed.Exception;
if (error == null || Response.HasStarted || HttpContext.RequestAborted.IsCancellationRequested)
return;
if (error is not (PodcastException or HttpRequestException or JsonException or TaskCanceledException))
return;
logger.LogError(error, "Podcast web request failed for {Action}", context.ActionDescriptor.DisplayName);
var status = error is PodcastException podcastError ? podcastError.StatusCode : 502;
var message = error is PodcastException known
? known.Message : "Le service de podcasts est indisponible. Reessayez plus tard.";
Response.StatusCode = status;
executed.ExceptionHandled = true;
executed.Result = context.ActionDescriptor.RouteValues["action"] == nameof(Index)
? View("Index", new PodcastCatalogueViewModel([], new HashSet<string>(), message))
: StatusCode(status, new ProblemDetails { Status = status, Title = message });
}
}

View file

@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Yavsc.Controllers;
[AttributeUsage(AttributeTargets.Method)]
public sealed class RawPayPalNotificationAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
context.ValueProviderFactories.RemoveType<FormValueProviderFactory>();
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
}
public void OnResourceExecuted(ResourceExecutedContext context) { }
}