Prepare podcast emissions using LiveFlow

Persist scheduled emissions, expose owner-only planning controls in PostIt and publish optional presentation-only announcements on Yavsc.Org. Preserve manual broadcasting and authenticated playback.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-02 14:08:22 +00:00
commit 4a5a3c8844
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
28 changed files with 5960 additions and 29 deletions

View file

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Middleware;
using Yavsc.Api.Services;
using Yavsc.Server.Helpers;
using Yavsc.Services;
@ -16,13 +17,40 @@ namespace Yavsc.ApiControllers;
[Authorize(Policy = "ApiScope")]
[Route(Constants.APIPrefix + "/podcasts")]
[TypeFilter(typeof(PodcastExceptionFilter))]
public sealed class PodcastController(ILiveProcessor processor) : ControllerBase
public sealed class PodcastController(ILiveProcessor processor, IPodcastScheduleService schedule) : ControllerBase
{
/// <summary>Lists live broadcasts and retained replays for signed-in listeners.</summary>
[HttpGet]
[ProducesResponseType<IReadOnlyList<PodcastResponse>>(StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<PodcastResponse>>> List(CancellationToken ct)
=> Ok(await processor.ListAsync(ct));
=> Ok(await schedule.ListAsync(User.GetUserId(), ct));
/// <summary>Public announcements contain presentation details only, never the stream.</summary>
[AllowAnonymous, HttpGet("announcements")]
[ProducesResponseType<IReadOnlyList<PodcastAnnouncementResponse>>(StatusCodes.Status200OK)]
public async Task<IActionResult> Announcements(CancellationToken ct)
=> Ok(await schedule.AnnouncementsAsync(ct));
/// <summary>Prepares a private emission; a nonempty announcement publishes its presentation.</summary>
[HttpPost("planned")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status201Created)]
public async Task<IActionResult> Prepare(PreparePodcastRequest request, CancellationToken ct)
{
var response = await schedule.PrepareAsync(User.GetUserId(), request, null, ct);
return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
}
/// <summary>Edits an owned emission before its first start.</summary>
[HttpPut("{id:guid}/planned")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
public async Task<IActionResult> Update(Guid id, PreparePodcastRequest request, CancellationToken ct)
=> Ok(await schedule.PrepareAsync(User.GetUserId(), request, id, ct));
/// <summary>Manually starts a prepared emission; retries retain the same broadcast identifier.</summary>
[HttpPost("{id:guid}/start")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
public async Task<IActionResult> Start(Guid id, CancellationToken ct)
=> Ok(await schedule.StartAsync(id, User.GetUserId(), ct));
/// <summary>Starts a broadcast owned by the current user.</summary>
[HttpPost]
@ -41,7 +69,7 @@ public sealed class PodcastController(ILiveProcessor processor) : ControllerBase
[ProducesResponseType<PodcastManifestResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<ActionResult<PodcastManifestResponse>> Get(Guid id, CancellationToken ct)
=> Ok(await processor.GetAsync(id, ct));
=> Ok(await schedule.GetAsync(id, User.GetUserId(), ct));
/// <summary>Commits an MPEG-TS segment. Identical retries are idempotent.</summary>
[HttpPut("{id:guid}/segments/{sequence:int}")]
@ -55,7 +83,8 @@ public sealed class PodcastController(ILiveProcessor processor) : ControllerBase
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
return Ok(await processor.AppendAsync(id, ownerId, sequence, duration, Request.Body, ct));
await processor.AppendAsync(id, ownerId, sequence, duration, Request.Body, ct);
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
}
/// <summary>Ends the broadcast and schedules preparation of its MP4 replay.</summary>
@ -65,7 +94,8 @@ public sealed class PodcastController(ILiveProcessor processor) : ControllerBase
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
return Ok(await processor.CompleteAsync(id, ownerId, ct));
await processor.CompleteAsync(id, ownerId, ct);
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
}
/// <summary>Serves a completed MP4 replay with authenticated byte-range support.</summary>
@ -126,7 +156,7 @@ public sealed class PodcastController(ILiveProcessor processor) : ControllerBase
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
await processor.DeleteAsync(id, ownerId, ct);
await schedule.DeleteAsync(id, ownerId, ct);
return NoContent();
}
}

View file

@ -2,6 +2,27 @@
@token = REPLACE_WITH_ACCESS_TOKEN
@id = REPLACE_WITH_PODCAST_ID
### Prepare a private emission (api scope; start/stop remain manual)
POST {{baseUrl}}/api/v1/podcasts/planned
Authorization: Bearer {{token}}
Content-Type: application/json
{"title":"Concert prepare","scheduledStartAt":"2026-12-01T20:00:00+01:00","plannedDurationMinutes":90}
### Edit before start and publish a public presentation; null/empty announcement unpublishes it
PUT {{baseUrl}}/api/v1/podcasts/{{id}}/planned
Authorization: Bearer {{token}}
Content-Type: application/json
{"title":"Concert prepare","scheduledStartAt":"2026-12-01T20:00:00+01:00","plannedDurationMinutes":90,"publicAnnouncement":"Venez ecouter notre concert"}
### Public presentation only (no token, no stream)
GET {{baseUrl}}/api/v1/podcasts/announcements
### Start the prepared emission manually, retaining its identifier (owner only)
POST {{baseUrl}}/api/v1/podcasts/{{id}}/start
Authorization: Bearer {{token}}
### Create a live broadcast
POST {{baseUrl}}/api/v1/podcasts
Authorization: Bearer {{token}}

View file

@ -0,0 +1,161 @@
#nullable enable
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Streaming;
using Yavsc.Models;
using Yavsc.Models.Streaming;
using Yavsc.Services;
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<IReadOnlyList<PodcastResponse>> ListAsync(string ownerId, CancellationToken ct);
Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct);
Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct);
Task DeleteAsync(Guid id, string ownerId, CancellationToken ct);
}
public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcessor processor,
IOptions<PodcastOptions> options) : IPodcastScheduleService
{
// The media store is single-process; serialize database/media lifecycle changes on that same host.
private static readonly SemaphoreSlim Gate = new(1);
public async Task<PodcastResponse> PrepareAsync(string ownerId, PreparePodcastRequest request, Guid? id, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Title) || request.Title.Trim().Length > 160
|| request.ScheduledStartAt == default || request.PlannedDurationMinutes < 1
|| request.PublicAnnouncement?.Length > 1023)
throw new PodcastException(400, "Titre, debut et duree positive en minutes requis.");
await Gate.WaitAsync(ct);
try
{
var flow = id.HasValue ? await OwnedAsync(id.Value, ownerId, ct) : null;
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.");
if (flow == null)
{
if (!await db.Users.AnyAsync(u => u.Id == ownerId, ct))
throw new PodcastException(404, "Compte introuvable.");
if (await db.LiveFlow.CountAsync(f => f.OwnerId == ownerId && f.PodcastId != null && !f.PodcastDeleted, ct)
>= options.Value.MaxOwnerPodcasts)
throw new PodcastException(413, "Nombre maximal d'emissions atteint. Supprimez une ancienne emission.");
flow = new LiveFlow
{
PodcastId = Guid.NewGuid(), OwnerId = ownerId, PreparedAt = DateTimeOffset.UtcNow,
Title = "", Pitch = "", MediaType = "application/vnd.apple.mpegurl", DifferedFileName = ""
};
db.LiveFlow.Add(flow);
}
flow.Title = request.Title.Trim();
flow.ScheduledStartAt = request.ScheduledStartAt.ToUniversalTime();
flow.PlannedDurationMinutes = request.PlannedDurationMinutes;
flow.PublicAnnouncement = request.PublicAnnouncement?.Trim() ?? "";
await db.SaveChangesAsync(ct);
await db.Entry(flow).Reference(f => f.Owner).LoadAsync(ct);
return Planned(flow);
}
finally { Gate.Release(); }
}
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct)
{
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);
}
finally { Gate.Release(); }
}
public async Task<IReadOnlyList<PodcastResponse>> ListAsync(string ownerId, CancellationToken ct)
{
var media = await processor.ListAsync(ct);
var flows = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.Where(f => f.PodcastId != null).ToListAsync(ct);
var byId = flows.ToDictionary(f => f.PodcastId!.Value);
var result = media.Where(p => !byId.TryGetValue(p.Id, out var f) || !f.PodcastDeleted)
.Select(p => byId.TryGetValue(p.Id, out var f) ? Enrich(p, f) : p).ToList();
var mediaIds = media.Select(p => p.Id).ToHashSet();
result.AddRange(flows.Where(f => !f.PodcastDeleted && f.StartedAt == null && f.OwnerId == ownerId
&& !mediaIds.Contains(f.PodcastId!.Value)).Select(Planned));
return result.OrderByDescending(p => p.CreatedAt).ToArray();
}
public async Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct)
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow == null) return await processor.GetAsync(id, ct);
if (flow.PodcastDeleted) throw new PodcastException(404, "Podcast introuvable.");
var podcast = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (podcast != null)
{
var manifest = await processor.GetAsync(id, ct);
return manifest with { Podcast = Enrich(manifest.Podcast, flow) };
}
if (flow.OwnerId != ownerId || flow.StartedAt != null)
throw new PodcastException(404, "Podcast introuvable.");
return new(Planned(flow), []);
}
public async Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct)
{
var flows = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.Where(f => f.PodcastId != null && !f.PodcastDeleted && f.ScheduledStartAt != null
&& f.PlannedDurationMinutes != null && f.PublicAnnouncement != "").ToListAsync(ct);
return flows.OrderBy(f => f.ScheduledStartAt).Select(f => new PodcastAnnouncementResponse(
f.PodcastId!.Value, f.Title, f.Owner.UserName ?? f.OwnerId, f.ScheduledStartAt!.Value,
f.PlannedDurationMinutes!.Value, f.PublicAnnouncement)).ToArray();
}
public async Task DeleteAsync(Guid id, string ownerId, CancellationToken ct)
{
await Gate.WaitAsync(ct);
try
{
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.");
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);
flow.PodcastDeleted = true;
await db.SaveChangesAsync(ct);
}
finally { Gate.Release(); }
}
private async Task<LiveFlow> OwnedAsync(Guid id, string ownerId, CancellationToken ct)
{
var flow = await db.LiveFlow.Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow == null || flow.PodcastDeleted) throw new PodcastException(404, "Emission introuvable.");
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut modifier cette emission.");
return flow;
}
private static PodcastResponse Planned(LiveFlow flow) => Enrich(new(
flow.PodcastId!.Value, flow.Title, flow.OwnerId, flow.Owner.UserName ?? flow.OwnerId,
flow.PreparedAt!.Value, flow.PreparedAt.Value, PodcastState.Planned, 0, 0, 0), flow);
private static PodcastResponse Enrich(PodcastResponse podcast, LiveFlow flow) => podcast with
{
FlowId = flow.Id, ScheduledStartAt = flow.ScheduledStartAt,
PlannedDurationMinutes = flow.PlannedDurationMinutes,
PublicAnnouncement = string.IsNullOrEmpty(flow.PublicAnnouncement) ? null : flow.PublicAnnouncement
};
}

View file

@ -8,6 +8,7 @@ public static class PodcastServiceCollectionExtensions
{
services.Configure<PodcastOptions>(configuration.GetSection("Podcast"));
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
services.AddSingleton<IPodcastReplayRemuxer, FfmpegPodcastReplayRemuxer>();
services.AddHostedService<PodcastReplayWorker>();
services.AddOpenApi("podcasts", options => options.ShouldInclude = description => description.GroupName == "podcasts");