Dons PayPal
This commit is contained in:
parent
20a44bfde1
commit
e3b4414ab1
45 changed files with 7476 additions and 9 deletions
538
src/test/Yavsc.Org.Tests/Controllers/PerformerDonationTests.cs
Normal file
538
src/test/Yavsc.Org.Tests/Controllers/PerformerDonationTests.cs
Normal file
|
|
@ -0,0 +1,538 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Models.Relationship;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Web.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Yavsc.Org.Tests.Controllers;
|
||||
|
||||
public sealed class PerformerDonationTests : IClassFixture<PerformerDonationTests.Factory>
|
||||
{
|
||||
private readonly Factory _factory;
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
public PerformerDonationTests(Factory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
factory.PayPal.Reset();
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.PerformerDonations.RemoveRange(db.PerformerDonations);
|
||||
if (!db.Users.Any(u => u.Id == "author"))
|
||||
{
|
||||
db.Users.AddRange(
|
||||
new ApplicationUser { Id = "author", UserName = "Author", Email = "author@example.test" },
|
||||
new ApplicationUser { Id = "listener", UserName = "Listener", Email = "listener@example.test" });
|
||||
}
|
||||
if (!db.Performers.Any(p => p.PerformerId == "author"))
|
||||
{
|
||||
db.Performers.Add(new PerformerProfile
|
||||
{
|
||||
PerformerId = "author", Active = true, SIREN = "123456789", WebSite = "",
|
||||
OrganizationAddress = new Location { Address = "Test" }
|
||||
});
|
||||
}
|
||||
db.SaveChanges();
|
||||
var performer = db.Performers.Single(p => p.PerformerId == "author");
|
||||
performer.DonationPayPalEmail = "author@payments.example";
|
||||
performer.Active = true;
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/Donation/Create/author")]
|
||||
[InlineData("/Donation/Settings")]
|
||||
public async Task Donation_pages_require_a_web_session(string path)
|
||||
{
|
||||
using var client = _factory.CreateClient(new() { AllowAutoRedirect = false });
|
||||
using var response = await client.GetAsync(path, Ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/signin", response.Headers.Location?.ToString());
|
||||
Assert.Empty(_factory.PayPal.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Performer_configures_only_their_own_recipient_and_can_disable_new_donations()
|
||||
{
|
||||
using var client = _factory.SignedInClient("author");
|
||||
using var response = await PostFormAsync(client, "/Donation/Settings", "/Donation/Settings", new()
|
||||
{
|
||||
["PayPalEmail"] = "new-recipient@payments.example", ["PerformerId"] = "listener"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("new-recipient@payments.example", await RecipientEmailAsync());
|
||||
using var disabled = await PostFormAsync(client, "/Donation/Settings", "/Donation/Settings", new() { ["PayPalEmail"] = "" });
|
||||
Assert.Equal(HttpStatusCode.Redirect, disabled.StatusCode);
|
||||
Assert.Null(await RecipientEmailAsync());
|
||||
using var listener = _factory.SignedInClient();
|
||||
using var create = await listener.GetAsync("/Donation/Create/author", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, create.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-an-email")]
|
||||
[InlineData("https://external.example/donate")]
|
||||
public async Task Invalid_recipient_setting_is_rejected(string value)
|
||||
{
|
||||
using var client = _factory.SignedInClient("author");
|
||||
using var response = await PostFormAsync(client, "/Donation/Settings", "/Donation/Settings", new() { ["PayPalEmail"] = value });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("author@payments.example", await RecipientEmailAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Non_performer_cannot_configure_a_recipient()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
using var response = await client.GetAsync("/Donation/Settings", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Contains("/Manage/SetActivity", await response.Content.ReadAsStringAsync(Ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Checkout_uses_the_stored_recipient_and_existing_paypal_configuration()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
Assert.Equal("listener", donation.DonorId);
|
||||
Assert.Equal("author@payments.example", donation.RecipientEmail);
|
||||
Assert.Equal(5m, donation.Amount);
|
||||
Assert.Equal(PerformerDonationState.AwaitingApproval, donation.State);
|
||||
var request = Assert.Single(_factory.PayPal.Requests);
|
||||
Assert.Equal("SetExpressCheckout", request["METHOD"]);
|
||||
Assert.Equal("author@payments.example", request["PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID"]);
|
||||
Assert.Equal("5.00", request["PAYMENTREQUEST_0_AMT"]);
|
||||
Assert.Equal("EUR", request["PAYMENTREQUEST_0_CURRENCYCODE"]);
|
||||
Assert.Equal("https://org.example/Donation/Notify", request["PAYMENTREQUEST_0_NOTIFYURL"]);
|
||||
Assert.StartsWith("https://org.example/Donation/Return?id=", request["RETURNURL"]);
|
||||
Assert.Equal(donation.Id.ToString("N"), request["PAYMENTREQUEST_0_INVNUM"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")]
|
||||
[InlineData("-5")]
|
||||
[InlineData("5.001")]
|
||||
public async Task Invalid_amount_does_not_initiate_paypal(string amount)
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
using var response = await PostFormAsync(client, "/Donation/Create/author", "/Donation/Create", new()
|
||||
{
|
||||
["PerformerId"] = "author", ["Amount"] = amount
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(_factory.PayPal.Requests);
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
Assert.Empty(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().PerformerDonations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Checkout_is_not_a_payment_and_confirmation_is_post_only_and_idempotent()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
using var returned = await client.GetAsync($"/Donation/Return/{donation.Id}?token={donation.CheckoutToken}&PayerID=untrusted", Ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, returned.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.AwaitingApproval, (await FindAsync(donation.Id)).State);
|
||||
using var get = await client.GetAsync($"/Donation/Confirm/{donation.Id}", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
|
||||
using var confirmed = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||
var completed = await FindAsync(donation.Id);
|
||||
Assert.Equal(PerformerDonationState.Completed, completed.State);
|
||||
Assert.NotNull(completed.TransactionId);
|
||||
Assert.NotNull(completed.CompletedAt);
|
||||
var payment = _factory.PayPal.Requests.Single(r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
Assert.Equal("approved-payer", payment["PAYERID"]);
|
||||
Assert.Equal(donation.Id.ToString("N"), payment["MSGSUBID"]);
|
||||
using var again = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Redirect, again.StatusCode);
|
||||
Assert.Single(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Another_user_and_a_substituted_checkout_token_cannot_confirm_the_donation()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
using var author = _factory.SignedInClient("author");
|
||||
using var details = await author.GetAsync($"/Donation/Details/{donation.Id}", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, details.StatusCode);
|
||||
using var wrong = await client.GetAsync($"/Donation/Return/{donation.Id}?token=another-token", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, wrong.StatusCode);
|
||||
Assert.DoesNotContain(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Payment_posts_require_antiforgery()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
using var response = await client.PostAsync("/Donation/Create",
|
||||
new FormUrlEncodedContent(new Dictionary<string, string> { ["PerformerId"] = "author", ["Amount"] = "5" }), Ct);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_factory.PayPal.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Changed_recipient_or_amount_in_paypal_approval_prevents_capture()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.MismatchApproval = true;
|
||||
using var response = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
Assert.DoesNotContain(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
Assert.Equal(PerformerDonationState.AwaitingApproval, (await FindAsync(donation.Id)).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pending_capture_is_not_displayed_as_paid_and_verified_ipn_completes_it_once()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.Pending = true;
|
||||
using var captured = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Redirect, captured.StatusCode);
|
||||
var pending = await FindAsync(donation.Id);
|
||||
Assert.Equal(PerformerDonationState.Pending, pending.State);
|
||||
Assert.Null(pending.CompletedAt);
|
||||
using var ipn = await NotifyAsync(donation.Id);
|
||||
Assert.Equal(HttpStatusCode.OK, ipn.StatusCode);
|
||||
using var duplicate = await NotifyAsync(donation.Id);
|
||||
Assert.Equal(HttpStatusCode.OK, duplicate.StatusCode);
|
||||
var completed = await FindAsync(donation.Id);
|
||||
Assert.Equal(PerformerDonationState.Completed, completed.State);
|
||||
Assert.NotNull(completed.CompletedAt);
|
||||
Assert.Single(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Capture_timeout_keeps_a_reconcilable_processing_state_without_charging_again()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.CaptureTimeout = true;
|
||||
using var response = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.GatewayTimeout, response.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.Processing, (await FindAsync(donation.Id)).State);
|
||||
using var retry = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
|
||||
using var ipn = await NotifyAsync(donation.Id);
|
||||
Assert.Equal(HttpStatusCode.OK, ipn.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.Completed, (await FindAsync(donation.Id)).State);
|
||||
Assert.Single(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, "author@payments.example", "5.00", "EUR", 400)]
|
||||
[InlineData(true, "someone-else@payments.example", "5.00", "EUR", 409)]
|
||||
[InlineData(true, "author@payments.example", "6.00", "EUR", 409)]
|
||||
[InlineData(true, "author@payments.example", "5.00", "USD", 409)]
|
||||
public async Task Forged_or_mismatched_ipn_cannot_mark_a_donation_paid(bool verified, string recipient, string amount, string currency, int status)
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.Pending = true;
|
||||
using var captured = await ConfirmAsync(client, donation.Id);
|
||||
_factory.PayPal.ValidNotification = verified;
|
||||
using var ipn = await NotifyAsync(donation.Id, recipient, amount, currency);
|
||||
Assert.Equal(status, (int)ipn.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.Pending, (await FindAsync(donation.Id)).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_confirmation_sends_only_one_capture()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.HoldCapture = true;
|
||||
var first = ConfirmAsync(client, donation.Id);
|
||||
await _factory.PayPal.CaptureStarted.Task.WaitAsync(Ct);
|
||||
try
|
||||
{
|
||||
using var second = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
|
||||
}
|
||||
finally { _factory.PayPal.ReleaseCapture.TrySetResult(); }
|
||||
using var response = await first;
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Single(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Completed", PerformerDonationState.Completed)]
|
||||
[InlineData("Denied", PerformerDonationState.Failed)]
|
||||
public async Task Notification_received_during_capture_is_not_overwritten_by_a_stale_pending_response(
|
||||
string paymentStatus, PerformerDonationState expected)
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
_factory.PayPal.Pending = true;
|
||||
_factory.PayPal.HoldCapture = true;
|
||||
var capturing = ConfirmAsync(client, donation.Id);
|
||||
await _factory.PayPal.CaptureStarted.Task.WaitAsync(Ct);
|
||||
try
|
||||
{
|
||||
using var notification = await NotifyAsync(donation.Id, paymentStatus: paymentStatus);
|
||||
Assert.Equal(HttpStatusCode.OK, notification.StatusCode);
|
||||
}
|
||||
finally { _factory.PayPal.ReleaseCapture.TrySetResult(); }
|
||||
using var response = await capturing;
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal(expected, (await FindAsync(donation.Id)).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Donation_keeps_its_original_recipient_when_the_performer_updates_their_settings()
|
||||
{
|
||||
using var donor = _factory.SignedInClient();
|
||||
var donation = await StartAsync(donor);
|
||||
using var author = _factory.SignedInClient("author");
|
||||
using var settings = await PostFormAsync(author, "/Donation/Settings", "/Donation/Settings", new()
|
||||
{
|
||||
["PayPalEmail"] = "new-recipient@payments.example"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Redirect, settings.StatusCode);
|
||||
using var confirmation = await ConfirmAsync(donor, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Redirect, confirmation.StatusCode);
|
||||
var payment = _factory.PayPal.Requests.Single(r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
Assert.Equal("author@payments.example", payment["PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID"]);
|
||||
Assert.Equal("author@payments.example", (await FindAsync(donation.Id)).RecipientEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task History_exposes_only_the_current_donors_payments()
|
||||
{
|
||||
using var donor = _factory.SignedInClient();
|
||||
var donation = await StartAsync(donor);
|
||||
var ownHistory = await donor.GetStringAsync("/Donation", Ct);
|
||||
Assert.Contains(donation.Id.ToString(), ownHistory);
|
||||
using var other = _factory.SignedInClient("author");
|
||||
var otherHistory = await other.GetStringAsync("/Donation", Ct);
|
||||
Assert.DoesNotContain(donation.Id.ToString(), otherHistory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Recipient_email_is_not_exposed_in_performer_json()
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var profile = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.Performers.AsNoTracking().SingleAsync(p => p.PerformerId == "author", Ct);
|
||||
Assert.DoesNotContain("author@payments.example", System.Text.Json.JsonSerializer.Serialize(profile));
|
||||
Assert.DoesNotContain("author@payments.example", Newtonsoft.Json.JsonConvert.SerializeObject(profile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task General_profile_edit_preserves_the_separately_configured_paypal_recipient()
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var profile = await db.Performers.AsNoTracking().Include(p => p.OrganizationAddress)
|
||||
.SingleAsync(p => p.PerformerId == "author", Ct);
|
||||
profile.DonationPayPalEmail = null;
|
||||
profile.ExerciseCountryCode = "en";
|
||||
profile.SIREN = "AB12CD34";
|
||||
var controller = ManageController(scope.ServiceProvider);
|
||||
Assert.IsType<RedirectToActionResult>(await controller.SetActivity(profile));
|
||||
Assert.Equal("author@payments.example", await RecipientEmailAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Performer_with_donation_history_cannot_be_deleted_by_unsetting_their_activity()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
await StartAsync(client);
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var controller = ManageController(scope.ServiceProvider);
|
||||
Assert.IsType<ConflictObjectResult>(await controller.UnsetActivity());
|
||||
Assert.Equal("author@payments.example", await RecipientEmailAsync());
|
||||
}
|
||||
|
||||
private static Yavsc.Controllers.ManageController ManageController(IServiceProvider services)
|
||||
{
|
||||
var controller = ActivatorUtilities.CreateInstance<Yavsc.Controllers.ManageController>(services);
|
||||
controller.ControllerContext = new ControllerContext
|
||||
{
|
||||
RouteData = new Microsoft.AspNetCore.Routing.RouteData(),
|
||||
ActionDescriptor = new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor(),
|
||||
HttpContext = new DefaultHttpContext
|
||||
{
|
||||
RequestServices = services,
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([
|
||||
new Claim("sub", "author"),
|
||||
new Claim("name", "Author"),
|
||||
new Claim(Yavsc.Constants.RoleClaimType, "Performer")
|
||||
], "test"))
|
||||
}
|
||||
};
|
||||
return controller;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cancel_return_has_no_side_effect_and_post_cancellation_prevents_capture()
|
||||
{
|
||||
using var client = _factory.SignedInClient();
|
||||
var donation = await StartAsync(client);
|
||||
using var get = await client.GetAsync($"/Donation/Cancel/{donation.Id}", Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, get.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.AwaitingApproval, (await FindAsync(donation.Id)).State);
|
||||
using var cancelled = await PostFormAsync(client, $"/Donation/Cancel/{donation.Id}", $"/Donation/CancelConfirm/{donation.Id}", new());
|
||||
Assert.Equal(HttpStatusCode.Redirect, cancelled.StatusCode);
|
||||
Assert.Equal(PerformerDonationState.Cancelled, (await FindAsync(donation.Id)).State);
|
||||
using var confirm = await ConfirmAsync(client, donation.Id);
|
||||
Assert.Equal(HttpStatusCode.Conflict, confirm.StatusCode);
|
||||
Assert.DoesNotContain(_factory.PayPal.Requests, r => r["METHOD"] == "DoExpressCheckoutPayment");
|
||||
}
|
||||
|
||||
private async Task<PerformerDonation> StartAsync(HttpClient client)
|
||||
{
|
||||
using var response = await PostFormAsync(client, "/Donation/Create/author", "/Donation/Create", new()
|
||||
{
|
||||
["PerformerId"] = "author", ["Amount"] = "5",
|
||||
["RecipientEmail"] = "attacker@payments.example", ["Currency"] = "USD", ["DonorId"] = "author"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.StartsWith("https://www.sandbox.paypal.com/", response.Headers.Location?.ToString());
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().PerformerDonations.AsNoTracking().SingleAsync(Ct);
|
||||
}
|
||||
|
||||
private Task<HttpResponseMessage> ConfirmAsync(HttpClient client, Guid id)
|
||||
=> PostFormAsync(client, "/Donation/Create/author", $"/Donation/Confirm/{id}", new());
|
||||
|
||||
private static async Task<HttpResponseMessage> PostFormAsync(HttpClient client, string page, string action, Dictionary<string, string> fields)
|
||||
{
|
||||
var html = await client.GetStringAsync(page, Ct);
|
||||
var match = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"");
|
||||
Assert.True(match.Success, "The page must render an antiforgery-protected form.");
|
||||
fields["__RequestVerificationToken"] = WebUtility.HtmlDecode(match.Groups[1].Value);
|
||||
return await client.PostAsync(action, new FormUrlEncodedContent(fields), Ct);
|
||||
}
|
||||
|
||||
private async Task<PerformerDonation> FindAsync(Guid id)
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().PerformerDonations.AsNoTracking().SingleAsync(d => d.Id == id, Ct);
|
||||
}
|
||||
|
||||
private async Task<string?> RecipientEmailAsync()
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Performers
|
||||
.Where(p => p.PerformerId == "author").Select(p => p.DonationPayPalEmail).SingleAsync(Ct);
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> NotifyAsync(Guid id, string recipient = "author@payments.example",
|
||||
string amount = "5.00", string currency = "EUR", string paymentStatus = "Completed")
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
return await client.PostAsync("/Donation/Notify", new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["invoice"] = id.ToString("N"), ["receiver_email"] = recipient, ["mc_gross"] = amount,
|
||||
["mc_currency"] = currency, ["txn_id"] = "payment-" + id.ToString("N")[..16],
|
||||
["payment_status"] = paymentStatus, ["txn_type"] = "express_checkout"
|
||||
}), Ct);
|
||||
}
|
||||
|
||||
public sealed class Factory : PodcastWebTests.Factory
|
||||
{
|
||||
public FakePayPal PayPal { get; } = new();
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.Configure<PayPalSettings>(settings =>
|
||||
{
|
||||
settings.Mode = "sandbox";
|
||||
settings.MerchantAccountUserName = "test-merchant";
|
||||
settings.Accounts = [new()
|
||||
{
|
||||
ApiUsername = "test-merchant", ApiPassword = "test-password", Signature = "test-signature"
|
||||
}];
|
||||
});
|
||||
services.AddTransient<IPayPalDonationGateway>(provider => new PayPalDonationGateway(
|
||||
new HttpClient(PayPal, disposeHandler: false), provider.GetRequiredService<IOptions<PayPalSettings>>()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FakePayPal : HttpMessageHandler
|
||||
{
|
||||
public ConcurrentQueue<Dictionary<string, string>> Requests { get; } = new();
|
||||
private readonly Dictionary<string, Dictionary<string, string>> _checkouts = new();
|
||||
public bool Pending { get; set; }
|
||||
public bool MismatchApproval { get; set; }
|
||||
public bool CaptureTimeout { get; set; }
|
||||
public bool ValidNotification { get; set; }
|
||||
public bool HoldCapture { get; set; }
|
||||
public TaskCompletionSource CaptureStarted { get; private set; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource ReleaseCapture { get; private set; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Requests.Clear();
|
||||
_checkouts.Clear();
|
||||
Pending = MismatchApproval = CaptureTimeout = HoldCapture = false;
|
||||
ValidNotification = true;
|
||||
CaptureStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
ReleaseCapture = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
var body = await request.Content!.ReadAsStringAsync(ct);
|
||||
if (request.RequestUri!.Host.StartsWith("ipnpb.", StringComparison.Ordinal))
|
||||
{
|
||||
Assert.StartsWith("cmd=_notify-validate&", body);
|
||||
return new(HttpStatusCode.OK) { Content = new StringContent(ValidNotification ? "VERIFIED" : "INVALID") };
|
||||
}
|
||||
Assert.Equal("https://api-3t.sandbox.paypal.com/nvp", request.RequestUri.AbsoluteUri);
|
||||
var fields = body.Split('&').Select(pair => pair.Split('=', 2))
|
||||
.ToDictionary(p => WebUtility.UrlDecode(p[0]), p => WebUtility.UrlDecode(p[1]));
|
||||
Requests.Enqueue(fields);
|
||||
Dictionary<string, string> result = new() { ["ACK"] = "Success" };
|
||||
switch (fields["METHOD"])
|
||||
{
|
||||
case "SetExpressCheckout":
|
||||
var token = "checkout-" + fields["PAYMENTREQUEST_0_INVNUM"];
|
||||
_checkouts[token] = fields;
|
||||
result["TOKEN"] = token;
|
||||
break;
|
||||
case "GetExpressCheckoutDetails":
|
||||
var checkout = _checkouts[fields["TOKEN"]];
|
||||
result["TOKEN"] = fields["TOKEN"];
|
||||
result["PAYERID"] = "approved-payer";
|
||||
foreach (var name in new[] { "INVNUM", "AMT", "CURRENCYCODE", "SELLERPAYPALACCOUNTID" })
|
||||
result["PAYMENTREQUEST_0_" + name] = checkout["PAYMENTREQUEST_0_" + name];
|
||||
if (MismatchApproval) result["PAYMENTREQUEST_0_AMT"] = "1000.00";
|
||||
break;
|
||||
case "DoExpressCheckoutPayment":
|
||||
CaptureStarted.TrySetResult();
|
||||
if (HoldCapture) await ReleaseCapture.Task.WaitAsync(ct);
|
||||
if (CaptureTimeout) throw new TaskCanceledException("Simulated PayPal timeout.");
|
||||
result["PAYMENTINFO_0_AMT"] = fields["PAYMENTREQUEST_0_AMT"];
|
||||
result["PAYMENTINFO_0_CURRENCYCODE"] = fields["PAYMENTREQUEST_0_CURRENCYCODE"];
|
||||
result["PAYMENTINFO_0_SELLERPAYPALACCOUNTID"] = fields["PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID"];
|
||||
result["PAYMENTINFO_0_PAYMENTSTATUS"] = Pending ? "Pending" : "Completed";
|
||||
result["PAYMENTINFO_0_TRANSACTIONID"] = "payment-" + fields["PAYMENTREQUEST_0_INVNUM"][..16];
|
||||
break;
|
||||
default: throw new InvalidOperationException("Unexpected PayPal operation.");
|
||||
}
|
||||
using var content = new FormUrlEncodedContent(result);
|
||||
return new(HttpStatusCode.OK) { Content = new StringContent(await content.ReadAsStringAsync(ct), Encoding.UTF8, "application/x-www-form-urlencoded") };
|
||||
}
|
||||
}
|
||||
}
|
||||
319
src/test/Yavsc.Org.Tests/Controllers/PodcastWebTests.cs
Normal file
319
src/test/Yavsc.Org.Tests/Controllers/PodcastWebTests.cs
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Claims;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using IdentityServer8;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Models.Relationship;
|
||||
using Yavsc.Web.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Yavsc.Org.Tests.Controllers;
|
||||
|
||||
public sealed class PodcastWebTests : IClassFixture<PodcastWebTests.Factory>
|
||||
{
|
||||
private readonly Factory _factory;
|
||||
private static readonly Guid PodcastId = Guid.Parse("bac67914-b844-4a15-94bf-49d82b0b0212");
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
public PodcastWebTests(Factory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
factory.Api.Reset();
|
||||
factory.Services.GetRequiredService<IOptions<SiteSettings>>().Value.ApiUrl = "https://api.example/";
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
if (!db.Users.Any(u => u.Id == "author"))
|
||||
{
|
||||
db.Users.AddRange(new ApplicationUser { Id = "author", UserName = "Author", Email = "author@example.test" },
|
||||
new ApplicationUser { Id = "listener", UserName = "Listener", Email = "listener@example.test" });
|
||||
}
|
||||
if (!db.Performers.Any(p => p.PerformerId == "author"))
|
||||
{
|
||||
db.Performers.Add(new PerformerProfile
|
||||
{
|
||||
PerformerId = "author", Active = true, DonationPayPalEmail = "author@payments.example",
|
||||
SIREN = "123456789", WebSite = "", OrganizationAddress = new Location { Address = "Test" }
|
||||
});
|
||||
}
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/Podcast")]
|
||||
[InlineData("/Podcast/bac67914-b844-4a15-94bf-49d82b0b0212/index.m3u8")]
|
||||
[InlineData("/Podcast/bac67914-b844-4a15-94bf-49d82b0b0212/segments/0.ts")]
|
||||
[InlineData("/Podcast/bac67914-b844-4a15-94bf-49d82b0b0212/replay.mp4")]
|
||||
public async Task Anonymous_requests_require_login_before_contacting_api(string path)
|
||||
{
|
||||
using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
using var response = await client.GetAsync(path, Ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/signin", response.Headers.Location?.ToString());
|
||||
Assert.Empty(_factory.Api.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Catalogue_uses_the_authority_user_token_without_an_api_client_or_external_donation_link()
|
||||
{
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/Podcast", Ct);
|
||||
var html = await response.Content.ReadAsStringAsync(Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains($"/Podcast/{PodcastId}/replay.mp4", html);
|
||||
Assert.Contains("/Donation/Create/author", html);
|
||||
Assert.Contains("/Donation/Settings", html);
|
||||
Assert.DoesNotContain("<script>unsafe-title</script>", html);
|
||||
Assert.Contains("<script>unsafe-title</script>", html);
|
||||
Assert.Contains("hls.light.min.js", html);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
var requests = _factory.Api.Requests.ToArray();
|
||||
var request = Assert.Single(requests);
|
||||
Assert.Equal("/api/v1/podcasts/", request.Path);
|
||||
Assert.StartsWith("Bearer ", request.Authorization);
|
||||
var token = new JwtSecurityTokenHandler().ReadJwtToken(request.Authorization![7..]);
|
||||
Assert.Contains(token.Claims, c => c.Type == "sub" && c.Value == "listener");
|
||||
Assert.Contains(token.Claims, c => c.Type == "scope" && c.Value == "api");
|
||||
Assert.Contains("api", token.Audiences);
|
||||
Assert.True(token.ValidTo - token.ValidFrom <= TimeSpan.FromMinutes(5));
|
||||
Assert.DoesNotContain(request.Authorization[7..], html);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Empty_catalogue_is_not_an_api_failure()
|
||||
{
|
||||
_factory.Api.Empty = true;
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/Podcast", Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("Aucun podcast", await response.Content.ReadAsStringAsync(Ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upstream_failure_returns_explicit_error_not_empty_catalogue()
|
||||
{
|
||||
_factory.Api.Status = HttpStatusCode.ServiceUnavailable;
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/Podcast", Ct);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
var html = await response.Content.ReadAsStringAsync(Ct);
|
||||
Assert.Contains("alert-danger", html);
|
||||
Assert.DoesNotContain("Aucun podcast", html);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Playlist_uses_authenticated_same_origin_segment_routes()
|
||||
{
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync($"/Podcast/{PodcastId}/index.m3u8", Ct);
|
||||
var playlist = await response.Content.ReadAsStringAsync(Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("application/vnd.apple.mpegurl", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Contains("#EXTINF:2.5,\n", playlist);
|
||||
Assert.Contains($"/Podcast/{PodcastId}/segments/0.ts", playlist);
|
||||
Assert.EndsWith("#EXT-X-ENDLIST\n", playlist);
|
||||
Assert.DoesNotContain("access_token", playlist);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Live_catalogue_without_donation_keeps_playlist_open()
|
||||
{
|
||||
_factory.Api.Live = true;
|
||||
using var client = SignedInClient();
|
||||
var html = await client.GetStringAsync("/Podcast", Ct);
|
||||
Assert.Contains($"/Podcast/{PodcastId}/index.m3u8", html);
|
||||
Assert.DoesNotContain("/Donation/Create/other-author", html);
|
||||
Assert.Contains("PayPal", html);
|
||||
var playlist = await client.GetStringAsync($"/Podcast/{PodcastId}/index.m3u8", Ct);
|
||||
Assert.DoesNotContain("#EXT-X-ENDLIST", playlist);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET")]
|
||||
[InlineData("HEAD")]
|
||||
public async Task Replay_preserves_byte_range_status_headers_and_head_semantics(string method)
|
||||
{
|
||||
using var client = SignedInClient();
|
||||
using var request = new HttpRequestMessage(new HttpMethod(method), $"/Podcast/{PodcastId}/replay.mp4");
|
||||
request.Headers.Range = new RangeHeaderValue(2, 5);
|
||||
using var response = await client.SendAsync(request, Ct);
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Equal("bytes 2-5/10", response.Content.Headers.ContentRange?.ToString());
|
||||
Assert.Equal(4, response.Content.Headers.ContentLength);
|
||||
Assert.Contains("bytes", response.Headers.AcceptRanges);
|
||||
Assert.Equal("video/mp4", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Equal(method == "HEAD" ? [] : new byte[] { 2, 3, 4, 5 },
|
||||
await response.Content.ReadAsByteArrayAsync(Ct));
|
||||
var forwarded = _factory.Api.Requests.Last();
|
||||
Assert.Equal(method, forwarded.Method);
|
||||
Assert.Equal("bytes=2-5", forwarded.Range);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unsatisfiable_replay_range_preserves_416_and_total_size()
|
||||
{
|
||||
using var client = SignedInClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"/Podcast/{PodcastId}/replay.mp4");
|
||||
request.Headers.Range = new RangeHeaderValue(100, 200);
|
||||
using var response = await client.SendAsync(request, Ct);
|
||||
Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);
|
||||
Assert.Equal("bytes */10", response.Content.Headers.ContentRange?.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_media_returns_404()
|
||||
{
|
||||
_factory.Api.Status = HttpStatusCode.NotFound;
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync($"/Podcast/{PodcastId}/segments/0.ts", Ct);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Local_hls_asset_is_served_without_a_cdn()
|
||||
{
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/js/hls.light.min.js", Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("Hls", await response.Content.ReadAsStringAsync(Ct));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://api.example/")]
|
||||
[InlineData("https://api.example/api/v1")]
|
||||
public async Task Api_base_url_preserves_the_existing_versioned_prefix(string address)
|
||||
{
|
||||
_factory.Services.GetRequiredService<IOptions<SiteSettings>>().Value.ApiUrl = address;
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/Podcast", Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("/api/v1/podcasts/", _factory.Api.Requests.Last().Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("http://api.example/")]
|
||||
public async Task Invalid_api_configuration_returns_503_without_network_access(string address)
|
||||
{
|
||||
_factory.Services.GetRequiredService<IOptions<SiteSettings>>().Value.ApiUrl = address;
|
||||
using var client = SignedInClient();
|
||||
using var response = await client.GetAsync("/Podcast", Ct);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
Assert.Empty(_factory.Api.Requests);
|
||||
}
|
||||
|
||||
private HttpClient SignedInClient() => _factory.SignedInClient();
|
||||
|
||||
public class Factory : TestWebApplicationFactory
|
||||
{
|
||||
public FakeApi Api { get; } = new();
|
||||
private readonly string _databaseName = "InMemory-PodcastWeb-" + Guid.NewGuid().ToString("N");
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:YavscConnection"] = _databaseName }));
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.AddSingleton<IAuthorizationPolicyProvider, DefaultAuthorizationPolicyProvider>();
|
||||
services.Configure<SiteSettings>(options =>
|
||||
{
|
||||
options.ApiUrl = "https://api.example/";
|
||||
options.ExternalUrl = "https://org.example/";
|
||||
});
|
||||
services.AddTransient(provider => new PodcastWebClient(
|
||||
new HttpClient(Api, disposeHandler: false),
|
||||
provider.GetRequiredService<IOptions<SiteSettings>>(),
|
||||
provider.GetRequiredService<IdentityServerTools>(),
|
||||
provider.GetRequiredService<IHttpContextAccessor>()));
|
||||
});
|
||||
}
|
||||
|
||||
public HttpClient SignedInClient(string userId = "listener")
|
||||
{
|
||||
var client = CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
var options = Services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>()
|
||||
.Get(IdentityConstants.ApplicationScheme);
|
||||
var principal = new ClaimsPrincipal(new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, userId),
|
||||
new Claim(ClaimTypes.Name, userId)
|
||||
], IdentityConstants.ApplicationScheme));
|
||||
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties
|
||||
{
|
||||
IssuedUtc = DateTimeOffset.UtcNow,
|
||||
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5)
|
||||
}, IdentityConstants.ApplicationScheme);
|
||||
client.DefaultRequestHeaders.Add("Cookie", $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FakeApi : HttpMessageHandler
|
||||
{
|
||||
public sealed record Request(string Path, string Method, string? Authorization, string? Range);
|
||||
public ConcurrentQueue<Request> Requests { get; } = new();
|
||||
public bool Empty { get; set; }
|
||||
public bool Live { get; set; }
|
||||
public HttpStatusCode Status { get; set; }
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Requests.Clear();
|
||||
Empty = false;
|
||||
Live = false;
|
||||
Status = HttpStatusCode.OK;
|
||||
}
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
var path = request.RequestUri!.AbsolutePath;
|
||||
Requests.Enqueue(new(path, request.Method.Method,
|
||||
request.Headers.Authorization?.ToString(), request.Headers.Range?.ToString()));
|
||||
if (Status != HttpStatusCode.OK)
|
||||
return Task.FromResult(new HttpResponseMessage(Status));
|
||||
var podcast = new PodcastResponse(PodcastId, "<script>unsafe-title</script>",
|
||||
Live ? "other-author" : "author", "Author", DateTimeOffset.UtcNow,
|
||||
DateTimeOffset.UtcNow, Live ? PodcastState.Live : PodcastState.Completed, 1, 188, 2.5)
|
||||
{
|
||||
Replay = Live ? null : new(PodcastReplayState.Ready, 10)
|
||||
};
|
||||
if (path == "/api/v1/podcasts/")
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = JsonContent.Create(Empty ? Array.Empty<PodcastResponse>() : [podcast])
|
||||
});
|
||||
if (path == $"/api/v1/podcasts/{PodcastId}")
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = JsonContent.Create(new PodcastManifestResponse(podcast, [new(0, 2.5, 188)]))
|
||||
});
|
||||
var range = request.Headers.Range?.Ranges.SingleOrDefault();
|
||||
var unsatisfiable = range?.From >= 10;
|
||||
var content = new ByteArrayContent(unsatisfiable ? [] : [2, 3, 4, 5]);
|
||||
if (range != null)
|
||||
content.Headers.ContentRange = unsatisfiable
|
||||
? new ContentRangeHeaderValue(10) : new ContentRangeHeaderValue(2, 5, 10);
|
||||
var result = new HttpResponseMessage(unsatisfiable ? HttpStatusCode.RequestedRangeNotSatisfiable
|
||||
: range != null ? HttpStatusCode.PartialContent : HttpStatusCode.OK) { Content = content };
|
||||
result.Headers.AcceptRanges.Add("bytes");
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue