Files
Febe/src/Febe.Web/Api/ConnectionApi.cs
T

66 lines
3.0 KiB
C#

using Febe.Core.Abstractions;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// The link to Instagram (spec §4.1, §10.3; contract in <c>Connection/PROTOCOLLO.md</c>) over <see cref="IConnectionService"/>.
/// Commands pass the Origin check of the security middleware like every other command (§13.1). Opening the login page
/// is not an engine action: Alberto uses the browser and the engine is still.
/// </summary>
public static class ConnectionApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/connection", async (IConnectionService connection, CancellationToken ct) =>
ApiHttp.Json(ToDto(await connection.GetStatusAsync(ct).ConfigureAwait(false)), FebeJsonContext.Default.ConnectionStatusDto));
endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) =>
{
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
: new BeginDrivingRequest(false);
await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false);
return Results.NoContent();
});
// «Ho finito» counts as having used the browser: «Riprendi» after a verification becomes active (mockup 11).
endpoints.MapPost("/api/connection/finish", async (IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
var result = await connection.FinishAsync(ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Json(new FinishDto(result.Connected, result.Message), FebeJsonContext.Default.FinishDto);
});
endpoints.MapPost("/api/connection/cancel", async (IConnectionService connection, CancellationToken ct) =>
{
await connection.CancelAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
endpoints.MapPost("/api/connection/disconnect", async (IConnectionService connection, CancellationToken ct) =>
{
await connection.DisconnectAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
}
public static ConnectionStatusDto ToDto(ConnectionStatus status)
{
ArgumentNullException.ThrowIfNull(status);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
}
public static string State(ConnectionState state) => state switch
{
ConnectionState.NotConnected => "notConnected",
ConnectionState.Connected => "connected",
ConnectionState.VerificationRequired => "verificationRequired",
_ => "browserUnavailable",
};
}