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:
Paul Schneider 2026-11-08 07:43:15 +00:00
commit b157dce4e4
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
54 changed files with 12996 additions and 50 deletions

View file

@ -8,6 +8,12 @@
@scopeId = 1
@templateId = REPLACE_WITH_MAILING_CRITERION
### Purge payment residues after the effective withdrawal's one-year anniversary
# 200: { users, subscriptions, payments, donations, legacyPayments }
# 401: no token; 403: token without Administrator role.
POST {{root}}/payment-residues/purge
Authorization: Bearer {{token}}
### Protected OpenAPI document (development only)
GET {{baseUrl}}/openapi/administration.json
Authorization: Bearer {{token}}

View file

@ -20,6 +20,13 @@ namespace Yavsc.ApiControllers.Administration;
[ServiceFilter(typeof(AdministrationExceptionFilter))]
public sealed class SiteAdministrationApiController(IAdministrationService service) : ControllerBase
{
[HttpPost("payment-residues/purge"), EndpointSummary("Purger les paiements techniques des comptes retires depuis au moins un an")]
[ProducesResponseType<PaymentResiduePurgeResult>(200)]
[Yavsc.Server.Helpers.ResourceUsageExempt]
public async Task<ActionResult<PaymentResiduePurgeResult>> PurgePaymentResidues(
[FromServices] Yavsc.Server.Helpers.IPaymentResidueService residues, CancellationToken ct)
=> Ok(await residues.PurgeAsync(ct));
[HttpGet("summary"), EndpointSummary("Statistiques du site et informations du logiciel")]
[ProducesResponseType<AdministrationSummary>(200)]
public async Task<ActionResult<AdministrationSummary>> Summary(CancellationToken ct)

View file

@ -90,10 +90,14 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
/// <summary>Ends the broadcast and schedules preparation of its MP4 replay.</summary>
[HttpPost("{id:guid}/complete")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
public async Task<ActionResult<PodcastResponse>> Complete(Guid id, CancellationToken ct)
public async Task<ActionResult<PodcastResponse>> Complete(Guid id,
[FromServices] IPodcastObsService obs, CancellationToken ct)
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
if ((await schedule.GetAsync(id, ownerId, ct)).Podcast.FlowId is not null
&& (await obs.StatusAsync(id, ownerId, ct)).Enabled)
await obs.DeactivateAsync(id, ownerId, ct);
await processor.CompleteAsync(id, ownerId, ct);
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
}

View file

@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Middleware;
using Yavsc.Api.Services;
using Yavsc.Server.Helpers;
namespace Yavsc.ApiControllers;
[ApiController, ApiExplorerSettings(GroupName = "podcasts")]
[Authorize(Policy = "ApiScope")]
[Route(Constants.APIPrefix + "/podcasts")]
[TypeFilter(typeof(PodcastExceptionFilter))]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class PodcastObsController(IPodcastObsService obs) : ControllerBase
{
[HttpPost("{id:guid}/obs"), EndpointSummary("Activer OBS pour une emission programmee et obtenir une cle a usage limite")]
[ProducesResponseType<PodcastObsCredentials>(200)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
[ProducesResponseType<ProblemDetails>(409)]
[ProducesResponseType<ProblemDetails>(429)]
[ProducesResponseType<ProblemDetails>(413)]
[ProducesResponseType<ProblemDetails>(503)]
public async Task<ActionResult<PodcastObsCredentials>> Activate(Guid id, CancellationToken ct)
=> Ok(await obs.ActivateAsync(id, User.GetUserId(), ct));
[HttpGet("{id:guid}/obs"), EndpointSummary("Consulter l'activation OBS et les erreurs de reception, sans exposer la cle")]
[ProducesResponseType<PodcastObsStatus>(200)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
public async Task<ActionResult<PodcastObsStatus>> Status(Guid id, CancellationToken ct)
=> Ok(await obs.StatusAsync(id, User.GetUserId(), ct));
[HttpDelete("{id:guid}/obs"), EndpointSummary("Revoquer la cle OBS et deconnecter le diffuseur")]
[ProducesResponseType(204)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
[ProducesResponseType<ProblemDetails>(503)]
[ResourceUsageRelief]
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
{
await obs.DeactivateAsync(id, User.GetUserId(), ct);
return NoContent();
}
[AllowAnonymous, HttpPost("relay/auth")]
[RequestSizeLimit(4096), ResourceUsageExempt]
[EndpointSummary("Authentification externe MediaMTX : publication avec cle, lecture interne et administration privees")]
[ProducesResponseType<PodcastRelayAuthorization>(200)]
[ProducesResponseType(401)]
public async Task<IActionResult> Authenticate(PodcastRelayAuthentication request, CancellationToken ct)
{
var authorization = await obs.AuthenticateAsync(request, ct);
return authorization is null ? Unauthorized() : Ok(authorization);
}
}

View file

@ -81,3 +81,18 @@ Authorization: Bearer {{token}}
### OpenAPI in development (requires an Administrator token)
GET {{baseUrl}}/openapi/podcasts.json
Authorization: Bearer {{token}}
### Activate OBS for an owned planned podcast (returns a one-time secret)
POST {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
### OBS activation status (never returns the stream key)
GET {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
### Revoke OBS and disconnect its publisher (allowed at consumption limit)
DELETE {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
# Activation: 403 other owner/closed account, 404 missing emission,
# 409 already started, 413 disk full, 429 consumption limit, 503 OBS disabled.
# relay/auth is called by MediaMTX, not by the end-user.

View file

@ -153,6 +153,7 @@ internal class Program
.UseRouting()
.UseAuthentication()
.UseCors("default")
.UseMiddleware<WithdrawnAccountMiddleware>()
.UseAuthorization()
.UseMiddleware<ResourceUsageTelemetryMiddleware>();
app.MapIdentityApi<ApplicationUser>().RequireAuthorization("ApiScope");

View file

@ -1,4 +1,5 @@
using Yavsc.ApiControllers.Administration;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Yavsc.Api.Services;
@ -9,6 +10,8 @@ public static class AdministrationServiceCollectionExtensions
services.AddHttpContextAccessor();
services.AddScoped<IAdministrationService, AdministrationService>();
services.AddScoped<AdministrationExceptionFilter>();
services.TryAddSingleton(TimeProvider.System);
services.AddScoped<Yavsc.Server.Helpers.IPaymentResidueService, Yavsc.Server.Helpers.PaymentResidueService>();
services.AddOpenApi(Constants.Administration, options =>
options.ShouldInclude = description => description.GroupName == Constants.Administration);
return services;

View file

@ -0,0 +1,33 @@
namespace Yavsc.Api.Services;
public sealed class PodcastObsOptions
{
public bool Enabled { get; set; }
public string ServerUrl { get; set; } = "";
public string RelayApiUrl { get; set; } = "http://127.0.0.1:9997/";
public string RelayReadUrl { get; set; } = "rtmp://127.0.0.1:1935/";
public string RelayUser { get; set; } = "yavsc";
public string RelayPassword { get; set; } = "";
public int ActivationMinutes { get; set; } = 30;
public int MaxDurationMinutes { get; set; } = 120;
public int MaxConcurrentBroadcasts { get; set; } = 2;
public bool AllowUnencryptedRtmp { get; set; }
public void Validate()
{
if (!Enabled) return;
if (!Uri.TryCreate(ServerUrl, UriKind.Absolute, out var server)
|| (server.Scheme != "rtmps" && !(AllowUnencryptedRtmp && server.Scheme == "rtmp"))
|| server.UserInfo.Length != 0 || server.Query.Length != 0 || server.Fragment.Length != 0
|| server.AbsolutePath is not ("" or "/")
|| !Uri.TryCreate(RelayApiUrl, UriKind.Absolute, out var api) || api.Scheme is not ("http" or "https")
|| api.UserInfo.Length != 0 || api.Query.Length != 0 || api.Fragment.Length != 0
|| !Uri.TryCreate(RelayReadUrl, UriKind.Absolute, out var read) || read.Scheme != "rtmp"
|| read.UserInfo.Length != 0 || read.Query.Length != 0 || read.Fragment.Length != 0
|| read.AbsolutePath is not ("" or "/")
|| RelayPassword.Length < 32 || string.IsNullOrWhiteSpace(RelayUser)
|| ActivationMinutes is < 1 or > 1440 || MaxDurationMinutes is < 1 or > 1440
|| MaxConcurrentBroadcasts is < 1 or > 16)
throw new InvalidOperationException("Invalid Podcast:Obs relay configuration. Use RTMPS, private relay addresses and a random password of at least 32 characters.");
}
}

View file

@ -0,0 +1,62 @@
#nullable enable
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace Yavsc.Api.Services;
public sealed record PodcastObsPublisher(Guid PodcastId, Guid ConnectionId, bool Secure);
public interface IPodcastObsRelay
{
Task<IReadOnlyList<PodcastObsPublisher>> PublishersAsync(CancellationToken ct);
Task KickAsync(Guid id, CancellationToken ct, Guid? connectionId = null);
}
public sealed class PodcastObsRelay(HttpClient http, IOptions<PodcastObsOptions> options) : IPodcastObsRelay
{
private HttpRequestMessage Request(HttpMethod method, string path)
{
var settings = options.Value;
settings.Validate();
var request = new HttpRequestMessage(method, new Uri(new Uri(settings.RelayApiUrl.TrimEnd('/') + "/"), path));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{settings.RelayUser}:{settings.RelayPassword}")));
return request;
}
public async Task<IReadOnlyList<PodcastObsPublisher>> PublishersAsync(CancellationToken ct)
{
var publishers = new List<PodcastObsPublisher>();
var page = 0;
while (true)
{
using var request = Request(HttpMethod.Get, $"v3/paths/list?itemsPerPage=100&page={page}");
using var response = await http.SendAsync(request, ct);
response.EnsureSuccessStatusCode();
using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct), cancellationToken: ct);
foreach (var item in document.RootElement.GetProperty("items").EnumerateArray())
if (item.GetProperty("ready").GetBoolean()
&& PodcastObsService.TryId(item.GetProperty("name").GetString() ?? "", out var id)
&& item.TryGetProperty("source", out var source) && source.ValueKind == JsonValueKind.Object
&& source.GetProperty("type").GetString() is "rtmpConn" or "rtmpsConn"
&& Guid.TryParse(source.GetProperty("id").GetString(), out var connection))
publishers.Add(new(id, connection, source.GetProperty("type").GetString() == "rtmpsConn"));
if (++page >= document.RootElement.GetProperty("pageCount").GetInt32()) break;
}
return publishers;
}
public async Task KickAsync(Guid id, CancellationToken ct, Guid? connectionId = null)
{
foreach (var publisher in (await PublishersAsync(ct)).Where(p => p.PodcastId == id
&& (!connectionId.HasValue || p.ConnectionId == connectionId)))
{
using var request = Request(HttpMethod.Post, $"v3/{(publisher.Secure ? "rtmps" : "rtmp")}/conns/kick/{publisher.ConnectionId}");
using var response = await http.SendAsync(request, ct);
if (response.StatusCode != HttpStatusCode.NotFound) response.EnsureSuccessStatusCode();
}
}
}

View file

@ -0,0 +1,158 @@
#nullable enable
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Streaming;
using Yavsc.Models;
using Yavsc.Models.Streaming;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Settings;
namespace Yavsc.Api.Services;
public interface IPodcastObsService
{
Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct);
Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastRelayAuthorization?> AuthenticateAsync(PodcastRelayAuthentication request, CancellationToken ct);
}
public sealed class PodcastObsService(ApplicationDbContext db, IOptions<PodcastObsOptions> options,
IOptions<ResourceUsageOptions> usageOptions, IPodcastObsRelay relay, TimeProvider clock,
ILogger<PodcastObsService> logger) : IPodcastObsService
{
private PodcastObsOptions Settings()
{
var value = options.Value;
if (!value.Enabled) throw new PodcastException(503, "L'entree OBS n'est pas configuree sur cette instance.");
value.Validate();
return value;
}
public Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct)
=> ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var settings = Settings();
var flow = await OwnedAsync(id, ownerId, ct);
if (flow.StartedAt is not null)
throw new PodcastException(409, "Cette emission a deja demarre. Preparez une nouvelle emission.");
if (flow.Owner.WithdrawalRequestedAt is not null)
throw new PodcastException(403, "Le compte est ferme.");
if (await QuotaReachedAsync(ownerId, ct))
throw new PodcastException(429, "Le seuil de consommation est atteint.");
if (flow.Owner.DiskUsage >= flow.Owner.GetEffectiveDiskQuota(clock.GetUtcNow()))
throw new PodcastException(413, "Le quota disque est atteint.");
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
flow.ObsKeyHash = Hash(key);
flow.ObsEnabledUntil = clock.GetUtcNow().AddMinutes(settings.ActivationMinutes);
flow.ObsConnectionId = null;
flow.ObsLastError = null;
await db.SaveChangesAsync(ct);
return new PodcastObsCredentials(settings.ServerUrl.TrimEnd('/'),
$"obs/{id:N}?key={key}", flow.ObsEnabledUntil.Value);
}, ct);
public async Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct)
{
var flow = await OwnedAsync(id, ownerId, ct, tracking: false);
return new(flow.ObsKeyHash is not null &&
(flow.StartedAt is not null || flow.ObsEnabledUntil > clock.GetUtcNow()),
flow.ObsEnabledUntil, flow.ObsLastError);
}
public async Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct)
{
var connectionId = await ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var flow = await OwnedAsync(id, ownerId, ct);
var connection = flow.ObsConnectionId;
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
await db.SaveChangesAsync(ct);
return connection;
}, ct);
if (connectionId.HasValue) await relay.KickAsync(id, ct, connectionId);
}
public async Task<PodcastRelayAuthorization?> AuthenticateAsync(PodcastRelayAuthentication request, CancellationToken ct)
{
var settings = Settings();
if (request.User == settings.RelayUser && EqualSecret(request.Password, settings.RelayPassword))
{
if (request.Action == "api" || request.Action == "read" && request.Protocol == "rtmp" && TryId(request.Path, out _))
return new(null);
}
if (request.Action == "publish" && request.Protocol == "rtmp" && TryId(request.Path, out var id))
{
var query = QueryHelpers.ParseQuery(request.Query ?? "");
if (query.TryGetValue("key", out var keys) && keys.Count == 1 && keys[0] is { Length: 64 } key
&& Guid.TryParse(request.Id, out var connectionId))
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.SingleOrDefaultAsync(f => f.PodcastId == id && !f.PodcastDeleted, ct);
if (flow is not null)
return await ResourceUsageTracker.WithUserLockAsync<PodcastRelayAuthorization?>(db, flow.OwnerId, async () =>
{
var current = await db.LiveFlow.Include(f => f.Owner).SingleAsync(f => f.PodcastId == id, ct);
await db.Entry(current).ReloadAsync(ct);
await db.Entry(current.Owner).ReloadAsync(ct);
if (current is { StartedAt: null, ObsKeyHash: not null, PodcastDeleted: false }
&& (current.ObsConnectionId is null || current.ObsConnectionId == connectionId)
&& current.ObsEnabledUntil > clock.GetUtcNow() && current.Owner.WithdrawalRequestedAt is null
&& EqualSecret(Hash(key), current.ObsKeyHash)
&& !await QuotaReachedAsync(current.OwnerId, ct)
&& current.Owner.DiskUsage < current.Owner.GetEffectiveDiskQuota(clock.GetUtcNow()))
{
current.ObsConnectionId = connectionId;
await db.SaveChangesAsync(ct);
return new(clock.GetUtcNow().AddMinutes(Math.Min(current.PlannedDurationMinutes ?? 1, settings.MaxDurationMinutes)));
}
logger.LogWarning("OBS publication refused for emission {PodcastId}", id);
return null;
}, ct);
}
}
logger.LogWarning("OBS relay authentication refused for action {Action}", request.Action is "publish" or "read" or "api" ? request.Action : "other");
return null;
}
private async Task<bool> QuotaReachedAsync(string ownerId, CancellationToken ct)
{
var record = await db.ResourceUsageRecords.AsNoTracking().Where(r => r.UserId == ownerId)
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id).FirstOrDefaultAsync(ct);
var policy = usageOptions.Value;
var gross = record is null ? 0m : policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
return ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m) >= policy.GetLimit(ownerId);
}
private async Task<LiveFlow> OwnedAsync(Guid id, string ownerId, CancellationToken ct, bool tracking = true)
{
var query = db.LiveFlow.Include(f => f.Owner).AsQueryable();
if (!tracking) query = query.AsNoTracking();
var flow = await query.SingleOrDefaultAsync(f => f.PodcastId == id && !f.PodcastDeleted, ct)
?? throw new PodcastException(404, "Emission introuvable.");
if (tracking)
{
await db.Entry(flow).ReloadAsync(ct);
await db.Entry(flow.Owner).ReloadAsync(ct);
}
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut activer OBS.");
return flow;
}
internal static bool TryId(string? path, out Guid id)
{
id = default;
return path is not null && path.StartsWith("obs/", StringComparison.Ordinal) && Guid.TryParseExact(path[4..], "N", out id);
}
private static string Hash(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
private static bool EqualSecret(string? actual, string expected)
=> actual is not null && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(actual), Encoding.UTF8.GetBytes(expected));
}

View file

@ -0,0 +1,267 @@
#nullable enable
using System.Diagnostics;
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Settings;
namespace Yavsc.Api.Services;
public sealed class PodcastObsWorker(IServiceScopeFactory scopes, IOptions<PodcastObsOptions> options,
ILogger<PodcastObsWorker> logger) : BackgroundService
{
private sealed record Capture(CancellationTokenSource Cancellation, Task Task);
private readonly Dictionary<Guid, Capture> captures = new();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!options.Value.Enabled) return;
options.Value.Validate();
try
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopes.CreateScope();
var relay = scope.ServiceProvider.GetRequiredService<IPodcastObsRelay>();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
foreach (var pair in captures.Where(c => c.Value.Task.IsCompleted).ToArray())
{
captures.Remove(pair.Key);
pair.Value.Cancellation.Dispose();
await pair.Value.Task;
}
foreach (var publisher in await relay.PublishersAsync(stoppingToken))
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.SingleOrDefaultAsync(f => f.PodcastId == publisher.PodcastId, stoppingToken);
var allowed = flow is { PodcastDeleted: false, ObsKeyHash: not null }
&& flow.ObsConnectionId == publisher.ConnectionId
&& flow.Owner.WithdrawalRequestedAt is null;
if (!allowed)
{
if (captures.TryGetValue(publisher.PodcastId, out var running)) running.Cancellation.Cancel();
await relay.KickAsync(publisher.PodcastId, stoppingToken, publisher.ConnectionId);
continue;
}
if (captures.ContainsKey(publisher.PodcastId)) continue;
if (flow!.StartedAt is not null || flow.ObsEnabledUntil <= DateTimeOffset.UtcNow
|| captures.Count >= options.Value.MaxConcurrentBroadcasts)
{
await relay.KickAsync(publisher.PodcastId, stoppingToken, publisher.ConnectionId);
await FailActivationAsync(publisher.PodcastId, publisher.ConnectionId, "Emission deja demarree, activation expiree ou capacite OBS atteinte.", stoppingToken);
continue;
}
var cancellation = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
captures.Add(publisher.PodcastId, new(cancellation,
CaptureAsync(publisher.PodcastId, flow.OwnerId, publisher.ConnectionId, cancellation.Token)));
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex)
{
logger.LogError(ex, "OBS relay scan failed; retrying");
}
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally
{
foreach (var capture in captures.Values) capture.Cancellation.Cancel();
await Task.WhenAll(captures.Values.Select(c => c.Task));
foreach (var capture in captures.Values) capture.Cancellation.Dispose();
}
}
private async Task CaptureAsync(Guid id, string ownerId, Guid connectionId, CancellationToken ct)
{
using var scope = scopes.CreateScope();
var services = scope.ServiceProvider;
var db = services.GetRequiredService<ApplicationDbContext>();
var processor = services.GetRequiredService<ILiveProcessor>();
var relay = services.GetRequiredService<IPodcastObsRelay>();
var media = services.GetRequiredService<IOptions<PodcastOptions>>().Value;
var directory = Path.Combine(media.RootPath, "obs-capture-" + id.ToString("N"));
string? error = null;
var started = false;
try
{
Directory.CreateDirectory(directory);
var podcast = await services.GetRequiredService<IPodcastScheduleService>().StartAsync(id, ownerId, ct, connectionId);
started = true;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(TimeSpan.FromMinutes(Math.Min(podcast.PlannedDurationMinutes ?? 1, options.Value.MaxDurationMinutes)));
await ReceiveAsync(id, ownerId, connectionId, directory, db, processor, media, services, deadline.Token);
}
catch (OperationCanceledException)
{
logger.LogInformation("OBS capture {PodcastId} stopped or reached its duration limit", id);
}
catch (Exception ex)
{
// FFmpeg diagnostics and request URLs can contain credentials: never persist or log them.
error = ex is PodcastException or ResourceUsageLimitException ? ex.Message : "Reception OBS impossible. Verifiez le relais, FFmpeg et l'encodage H.264/AAC.";
logger.LogError("OBS capture {PodcastId} failed ({ErrorType})", id, ex.GetType().Name);
}
finally
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await relay.KickAsync(id, timeout.Token, connectionId);
db.ChangeTracker.Clear();
var flow = await db.LiveFlow.Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, timeout.Token);
if (flow is not null)
{
if (flow.ObsKeyHash is null && flow.ObsConnectionId is null) error = null;
if (started && flow.Owner.WithdrawalRequestedAt is null)
await processor.CompleteAsync(id, ownerId, timeout.Token);
if (flow.ObsConnectionId == connectionId || flow.ObsKeyHash is null)
{
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
flow.ObsLastError = error;
}
await db.SaveChangesAsync(timeout.Token);
}
}
catch (Exception ex)
{
logger.LogError("OBS capture {PodcastId} cleanup failed ({ErrorType}); operator intervention required", id, ex.GetType().Name);
await FailActivationAsync(id, connectionId, "Finalisation OBS impossible ; intervention de l'administration requise.", CancellationToken.None);
}
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
private async Task ReceiveAsync(Guid id, string ownerId, Guid connectionId, string directory, ApplicationDbContext db,
ILiveProcessor processor, PodcastOptions media, IServiceProvider services, CancellationToken ct)
{
var settings = options.Value;
var input = new UriBuilder(new Uri(new Uri(settings.RelayReadUrl.TrimEnd('/') + "/"), $"obs/{id:N}"))
{ Query = $"user={Uri.EscapeDataString(settings.RelayUser)}&pass={Uri.EscapeDataString(settings.RelayPassword)}" };
var start = new ProcessStartInfo(media.FfmpegPath)
{
UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true,
CreateNoWindow = true, WorkingDirectory = directory
};
foreach (var argument in new[]
{
"-nostdin", "-hide_banner", "-loglevel", "error", "-rw_timeout", "15000000",
"-i", input.Uri.AbsoluteUri, "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy",
"-f", "segment", "-segment_format", "mpegts", "-segment_time", "2",
"-segment_list", "pipe:1", "-segment_list_type", "csv", "segment-%08d.ts"
}) start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new IOException("FFmpeg could not start.");
var diagnostics = DrainAsync(process.StandardError);
using var monitoring = CancellationTokenSource.CreateLinkedTokenSource(ct);
var guard = GuardBufferAsync(directory, media.MaxSegmentBytes, monitoring.Token);
var next = 0;
var total = 0L;
var revoked = false;
try
{
while (true)
{
using var idle = CancellationTokenSource.CreateLinkedTokenSource(ct);
idle.CancelAfter(TimeSpan.FromSeconds(20));
var read = process.StandardOutput.ReadLineAsync(idle.Token).AsTask();
if (await Task.WhenAny(read, guard) == guard) await guard;
var line = await read;
if (line is null) break;
var fields = line.Split(',');
if (fields.Length != 3 || fields[0] != $"segment-{next:D8}.ts"
|| !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var begin)
|| !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var end)
|| !double.IsFinite(end - begin) || end - begin <= 0 || end - begin > 15)
throw new PodcastException(400, "Segments OBS invalides ; configurez H.264/AAC et des images cles toutes les deux secondes.");
var path = Path.Combine(directory, fields[0]);
var bytes = new FileInfo(path).Length;
if (bytes == 0 || bytes > media.MaxSegmentBytes)
throw new PodcastException(413, "Segment OBS trop volumineux ; reduisez le debit et l'intervalle des images cles.");
total = checked(total + bytes);
await ResourceUsageTracker.RecordStorageAsync(db, ownerId, ownerId, $"podcast/{id:N}", total, ct,
write: async () =>
{
var user = await db.Users.SingleAsync(u => u.Id == ownerId, ct);
await db.Entry(user).ReloadAsync(ct);
var flow = await db.LiveFlow.SingleAsync(f => f.PodcastId == id, ct);
await db.Entry(flow).ReloadAsync(ct);
if (user.WithdrawalRequestedAt is not null || flow.ObsKeyHash is null
|| flow.ObsConnectionId != connectionId || flow.PodcastDeleted)
{
revoked = true;
throw new OperationCanceledException("OBS activation revoked or account closed.", ct);
}
if (bytes > user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow) - user.DiskUsage)
throw new PodcastException(413, "Quota disque atteint.");
await using var stream = File.OpenRead(path);
await processor.AppendAsync(id, ownerId, next, end - begin, stream, ct);
user.DiskUsage = checked(user.DiskUsage + bytes);
},
policy: services.GetRequiredService<IOptions<ResourceUsageOptions>>().Value,
bandwidthMb: (decimal)bytes / (1024m * 1024m));
File.Delete(path);
next++;
}
await process.WaitForExitAsync(ct);
if (process.ExitCode != 0 || next == 0) throw new IOException("FFmpeg ingest failed or produced no media.");
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested && !revoked)
{
throw new PodcastException(408, "Aucun segment OBS recu depuis vingt secondes ; verifiez l'encodeur et la connexion.");
}
finally
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
await process.WaitForExitAsync(CancellationToken.None);
await diagnostics;
monitoring.Cancel();
try { await guard; }
catch (OperationCanceledException) when (monitoring.IsCancellationRequested) { }
}
}
private static async Task GuardBufferAsync(string directory, int maxSegmentBytes, CancellationToken ct)
{
while (true)
{
var pending = 0L;
foreach (var path in Directory.EnumerateFiles(directory, "*.ts"))
{
var file = new FileInfo(path);
if (!file.Exists) continue;
var bytes = file.Length;
if (bytes > maxSegmentBytes || (pending += bytes) > 64L * 1024 * 1024)
throw new PodcastException(413, "Capture OBS trop volumineuse ou stockage trop lent ; reduisez le debit.");
}
await Task.Delay(100, ct);
}
}
private static async Task DrainAsync(StreamReader reader)
{
var buffer = new char[1024];
while (await reader.ReadAsync(buffer) != 0) { }
}
private async Task FailActivationAsync(Guid id, Guid connectionId, string message, CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var flow = await db.LiveFlow.SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow is null || flow.ObsKeyHash is not null && flow.ObsConnectionId != connectionId) return;
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
flow.ObsLastError = message;
await db.SaveChangesAsync(ct);
}
}

View file

@ -12,7 +12,7 @@ namespace Yavsc.Api.Services;
public interface IPodcastScheduleService
{
Task<PodcastResponse> PrepareAsync(string ownerId, PreparePodcastRequest request, Guid? id, CancellationToken ct);
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null);
Task<IReadOnlyList<PodcastResponse>> ListAsync(string ownerId, CancellationToken ct);
Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct);
Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct);
@ -35,6 +35,8 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
try
{
var flow = id.HasValue ? await OwnedAsync(id.Value, ownerId, ct) : null;
if (flow?.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez l'entree OBS avant de modifier l'emission.");
if (flow != null && (flow.StartedAt != null
|| (await processor.ListAsync(ct)).Any(p => p.Id == id)))
throw new PodcastException(409, "Une emission demarree ne peut plus etre reprogrammee.");
@ -63,21 +65,33 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
finally { Gate.Release(); }
}
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct)
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null)
{
await Gate.WaitAsync(ct);
try
{
var flow = await OwnedAsync(id, ownerId, ct);
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (existing != null && existing.State != PodcastState.Live)
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
if (flow.StartedAt != null && existing == null)
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
flow.StartedAt ??= podcast.CreatedAt;
await db.SaveChangesAsync(ct);
return Enrich(podcast, flow);
return await Yavsc.Server.Helpers.ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var flow = await OwnedAsync(id, ownerId, ct);
await db.Entry(flow).ReloadAsync(ct);
await db.Entry(flow.Owner).ReloadAsync(ct);
if (flow.Owner.WithdrawalRequestedAt is not null)
throw new PodcastException(403, "Le compte est ferme.");
if (obsConnectionId.HasValue && (flow.ObsConnectionId != obsConnectionId
|| flow.ObsKeyHash is null || flow.ObsEnabledUntil <= DateTimeOffset.UtcNow))
throw new OperationCanceledException("OBS connection revoked or activation expired.", ct);
if (!obsConnectionId.HasValue && flow.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez OBS avant de demarrer une capture PostIt.");
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (existing != null && existing.State != PodcastState.Live)
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
if (flow.StartedAt != null && existing == null)
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
flow.StartedAt ??= podcast.CreatedAt;
await db.SaveChangesAsync(ct);
return Enrich(podcast, flow);
}, ct);
}
finally { Gate.Release(); }
}
@ -130,10 +144,24 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
var flow = await db.LiveFlow.SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow == null) { await processor.DeleteAsync(id, ownerId, ct); return; }
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut supprimer ce podcast.");
if (flow.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez l'entree OBS avant de supprimer l'emission.");
var podcast = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (podcast?.State == PodcastState.Live)
throw new PodcastException(409, "Terminez le direct avant de le supprimer.");
if (podcast != null) await processor.DeleteAsync(id, ownerId, ct);
var storage = await db.ResourceStorageRecords.AsNoTracking()
.SingleOrDefaultAsync(r => r.UserId == ownerId && r.Path == $"podcast/{id:N}", ct);
if (storage is not null)
{
await Yavsc.Server.Helpers.ResourceUsageTracker.RecordStorageAsync(db, ownerId,
flow.OwnerId, storage.Path, 0, ct, write: async () =>
{
var owner = await db.Users.SingleAsync(u => u.Id == ownerId, ct);
await db.Entry(owner).ReloadAsync(ct);
owner.DiskUsage = Math.Max(0, owner.DiskUsage - storage.Bytes);
});
}
flow.PodcastDeleted = true;
await db.SaveChangesAsync(ct);
}

View file

@ -7,6 +7,11 @@ public static class PodcastServiceCollectionExtensions
public static IServiceCollection AddPodcasts(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<PodcastOptions>(configuration.GetSection("Podcast"));
services.Configure<PodcastObsOptions>(configuration.GetSection("Podcast:Obs"));
services.AddScoped<IPodcastObsService, PodcastObsService>();
services.AddHttpClient<IPodcastObsRelay, PodcastObsRelay>(client => client.Timeout = TimeSpan.FromSeconds(10))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
services.AddHostedService<PodcastObsWorker>();
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
services.AddSingleton<IPodcastReplayRemuxer, FfmpegPodcastReplayRemuxer>();