Créer un client
Authentifiez-vous avec votre jeton API. Le jeton n'est envoyé qu'à l'hôte appelé.
import { ApiKeyAuthenticationProvider, ApiKeyLocation } from '@microsoft/kiota-abstractions';
import { DefaultRequestAdapter } from '@microsoft/kiota-bundle';
import { createLeagueDispatcherClient, type LeagueDispatcherClient } from '@leaguedispatcher/sdk';
export function createClient(): LeagueDispatcherClient {
const token = process.env.LEAGUE_DISPATCHER_API_TOKEN;
if (!token) throw new Error('Set LEAGUE_DISPATCHER_API_TOKEN to a league API token.');
const baseUrl = process.env.LEAGUE_DISPATCHER_BASE_URL ?? 'https://api.leaguedispatcher.com/v1';
// The token goes in the X-Api-Key header, over HTTPS, and only to the host you call.
const auth = new ApiKeyAuthenticationProvider(token, 'X-Api-Key', ApiKeyLocation.Header, new Set([new URL(baseUrl).hostname]));
const adapter = new DefaultRequestAdapter(auth);
adapter.baseUrl = baseUrl;
return createLeagueDispatcherClient(adapter);
}
import os
from urllib.parse import urlparse
from kiota_abstractions.authentication.api_key_authentication_provider import (
ApiKeyAuthenticationProvider,
KeyLocation,
)
from kiota_bundle.default_request_adapter import DefaultRequestAdapter
from leaguedispatcher.league_dispatcher_client import LeagueDispatcherClient
def create_client() -> LeagueDispatcherClient:
token = os.environ.get("LEAGUE_DISPATCHER_API_TOKEN")
if not token:
raise RuntimeError("Set LEAGUE_DISPATCHER_API_TOKEN to a league API token.")
base_url = os.environ.get("LEAGUE_DISPATCHER_BASE_URL", "https://api.leaguedispatcher.com/v1")
# The token goes in the X-Api-Key header, over HTTPS, and only to the host you call.
auth = ApiKeyAuthenticationProvider(
KeyLocation.Header, token, "X-Api-Key", [urlparse(base_url).hostname or ""]
)
adapter = DefaultRequestAdapter(auth)
adapter.base_url = base_url
return LeagueDispatcherClient(adapter)
using LeagueDispatcher.Sdk;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Bundle;
public static class LeagueClient
{
public static LeagueDispatcherClient Create()
{
var token = Environment.GetEnvironmentVariable("LEAGUE_DISPATCHER_API_TOKEN")
?? throw new InvalidOperationException("Set LEAGUE_DISPATCHER_API_TOKEN to a league API token.");
var baseUrl = Environment.GetEnvironmentVariable("LEAGUE_DISPATCHER_BASE_URL") ?? "https://api.leaguedispatcher.com/v1";
// The token goes in the X-Api-Key header, over HTTPS, and only to the host you call.
var auth = new ApiKeyAuthenticationProvider(token, "X-Api-Key",
ApiKeyAuthenticationProvider.KeyLocation.Header, new Uri(baseUrl).Host);
var adapter = new DefaultRequestAdapter(auth) { BaseUrl = baseUrl };
return new LeagueDispatcherClient(adapter);
}
}
Ajouter, renommer et retirer un joueur
Modifiez un joueur à la fois ; la ligue crée l’identifiant d’un nouveau joueur. Les modifications faites entre-temps sur d’autres appareils sont conservées. L’ajout envoie un en-tête Idempotency-Key : il peut être renvoyé sans risque.
import { randomUUID } from 'node:crypto';
import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import type { Player } from '@leaguedispatcher/sdk/models';
/** Makes a create safe to retry: a repeat with the same key answers what the first call created. */
const IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
/**
* Adds a player to the roster; the league creates the id and the player starts Not available.
* When the answer is lost (timeout, dropped connection), call again with the same idempotencyKey:
* the league answers the player it already added instead of adding a second one.
*/
export async function addPlayer(
client: LeagueDispatcherClient,
name: string,
idempotencyKey: string = randomUUID(),
): Promise<Player | undefined> {
return client.players.post({ name }, { headers: { [IDEMPOTENCY_KEY_HEADER]: idempotencyKey } });
}
export async function renamePlayer(client: LeagueDispatcherClient, playerId: string, name: string): Promise<void> {
await client.players.byPlayerId(playerId).put({ name });
}
/** Removes the player from the roster (and from their court); their games stay. */
export async function removePlayer(client: LeagueDispatcherClient, playerId: string): Promise<void> {
await client.players.byPlayerId(playerId).delete();
}
import uuid
from typing import Optional
from leaguedispatcher.league_dispatcher_client import LeagueDispatcherClient
from leaguedispatcher.models.create_player_request import CreatePlayerRequest
from leaguedispatcher.models.player import Player
from leaguedispatcher.models.update_player_request import UpdatePlayerRequest
from leaguedispatcher.players.players_request_builder import PlayersRequestBuilder
# Makes a create safe to retry: a repeat with the same key answers what the first call created.
IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"
async def add_player(
client: LeagueDispatcherClient, name: str, idempotency_key: Optional[str] = None
) -> Optional[Player]:
"""Adds a player to the roster; the league creates the id and the player starts Not available.
When the answer is lost (timeout, dropped connection), call again with the same idempotency_key:
the league answers the player it already added instead of adding a second one.
"""
config = PlayersRequestBuilder.PlayersRequestBuilderPostRequestConfiguration()
config.headers.add(IDEMPOTENCY_KEY_HEADER, idempotency_key or str(uuid.uuid4()))
return await client.players.post(CreatePlayerRequest(name=name), config)
async def rename_player(client: LeagueDispatcherClient, player_id: str, name: str) -> None:
await client.players.by_player_id(player_id).put(UpdatePlayerRequest(name=name))
async def remove_player(client: LeagueDispatcherClient, player_id: str) -> None:
"""Removes the player from the roster (and from their court); their games stay."""
await client.players.by_player_id(player_id).delete()
using LeagueDispatcher.Sdk;
using LeagueDispatcher.Sdk.Models;
public static class ManagePlayers
{
/// <summary>Makes a create safe to retry: a repeat with the same key answers what the first call created.</summary>
public const string IdempotencyKeyHeader = "Idempotency-Key";
/// <summary>
/// Adds a player to the roster; the league creates the id and the player starts Not available.
/// When the answer is lost (timeout, dropped connection), call again with the same idempotencyKey:
/// the league answers the player it already added instead of adding a second one.
/// </summary>
public static Task<Player?> AddAsync(LeagueDispatcherClient client, string name, string? idempotencyKey = null) =>
client.Players.PostAsync(new CreatePlayerRequest { Name = name },
config => config.Headers.Add(IdempotencyKeyHeader, idempotencyKey ?? Guid.NewGuid().ToString()));
public static Task RenameAsync(LeagueDispatcherClient client, string playerId, string name) =>
client.Players[playerId].PutAsync(new UpdatePlayerRequest { Name = name });
/// <summary>Removes the player from the roster (and from their court); their games stay.</summary>
public static Task RemoveAsync(LeagueDispatcherClient client, string playerId) =>
client.Players[playerId].DeleteAsync();
}
Lancer la partie suivante
Demandez la partie suivante à l'algorithme de la ligue et lancez-la (permission Répartition).
import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
/** Returns the court the game started on, or undefined when no game can start. */
export async function dispatchNextGame(client: LeagueDispatcherClient): Promise<string | undefined> {
// The league's matchmaking algorithm proposes the next game.
const next = await client.gameDay.nextGames.get();
const proposal = next?.propositions?.[0];
if (!proposal?.courtId || !proposal.players) {
console.log('No game can start right now.');
return undefined;
}
await client.gameDay.courts.byCourtId(proposal.courtId).game.post({
playerIds: proposal.players.map(p => p.id!),
teams: proposal.teams,
});
console.log(`Game started on court ${proposal.courtId}`);
return proposal.courtId;
}
from typing import Optional
from leaguedispatcher.league_dispatcher_client import LeagueDispatcherClient
from leaguedispatcher.models.dispatch_game_request import DispatchGameRequest
async def dispatch_next_game(client: LeagueDispatcherClient) -> Optional[str]:
"""Returns the court the game started on, or None when no game can start."""
# The league's matchmaking algorithm proposes the next game.
proposals = await client.game_day.next_games.get()
proposal = proposals.propositions[0] if proposals and proposals.propositions else None
if not proposal or not proposal.court_id or not proposal.players:
print("No game can start right now.")
return None
body = DispatchGameRequest(
player_ids=[p.id for p in proposal.players if p.id],
teams=proposal.teams,
)
await client.game_day.courts.by_court_id(proposal.court_id).game.post(body)
print(f"Game started on court {proposal.court_id}")
return proposal.court_id
using LeagueDispatcher.Sdk;
using LeagueDispatcher.Sdk.Models;
public static class DispatchNextGame
{
/// <returns>The court the game started on, or null when no game can start.</returns>
public static async Task<string?> RunAsync(LeagueDispatcherClient client)
{
// The league's matchmaking algorithm proposes the next game.
var next = await client.GameDay.NextGames.GetAsync();
var proposal = next?.Propositions?.FirstOrDefault();
if (proposal?.CourtId == null || proposal.Players == null)
{
Console.WriteLine("No game can start right now.");
return null;
}
await client.GameDay.Courts[proposal.CourtId].Game.PostAsync(new DispatchGameRequest
{
PlayerIds = proposal.Players.Select(p => p.Id!).ToList(),
Teams = proposal.Teams,
});
Console.WriteLine($"Game started on court {proposal.CourtId}");
return proposal.CourtId;
}
}
Terminer une partie
Enregistrez les gagnants et le score d'une partie (permission Terminer la partie).
import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
export async function finishGame(client: LeagueDispatcherClient, courtId: string): Promise<void> {
const state = await client.gameDay.get();
const court = state?.courts?.find(c => c.id === courtId);
if (!court?.players) throw new Error(`Court ${courtId} not found`);
const names = new Map((state?.players ?? []).map(p => [p.id, p.name]));
// The first half of the court's players won.
const winnerIds = court.players.slice(0, court.players.length / 2);
await client.gameDay.courts.byCourtId(courtId).game.finish.post({
winners: {
winnerScore: 21,
looserScore: 15,
players: winnerIds.map(id => ({ id, name: names.get(id) })),
},
// The game this finishes: a retry can never finish the next game on the court.
gameStartTime: court.lastPlayDate,
});
}
from leaguedispatcher.league_dispatcher_client import LeagueDispatcherClient
from leaguedispatcher.models.finish_game_request import FinishGameRequest
from leaguedispatcher.models.game_player import GamePlayer
from leaguedispatcher.models.winners import Winners
async def finish_game(client: LeagueDispatcherClient, court_id: str) -> None:
state = await client.game_day.get()
court = next((c for c in (state.courts if state else None) or [] if c.id == court_id), None)
if not court or not court.players:
raise RuntimeError(f"Court {court_id} not found")
names = {p.id: p.name for p in (state.players if state else None) or []}
# The first half of the court's players won.
winner_ids = court.players[: len(court.players) // 2]
await client.game_day.courts.by_court_id(court_id).game.finish.post(
FinishGameRequest(
winners=Winners(
winner_score=21,
looser_score=15,
players=[GamePlayer(id=pid, name=names.get(pid)) for pid in winner_ids],
),
# The game this finishes: a retry can never finish the next game on the court.
game_start_time=court.last_play_date,
)
)
using LeagueDispatcher.Sdk;
using LeagueDispatcher.Sdk.Models;
public static class FinishGame
{
public static async Task RunAsync(LeagueDispatcherClient client, string courtId)
{
var state = await client.GameDay.GetAsync();
var court = state?.Courts?.FirstOrDefault(c => c.Id == courtId)
?? throw new InvalidOperationException($"Court {courtId} not found");
var names = (state?.Players ?? []).ToDictionary(p => p.Id!, p => p.Name);
// The first half of the court's players won.
var winnerIds = court.Players!.Take(court.Players!.Count / 2);
await client.GameDay.Courts[courtId].Game.Finish.PostAsync(new FinishGameRequest
{
Winners = new Winners
{
WinnerScore = 21,
LooserScore = 15,
Players = winnerIds.Select(id => new GamePlayer { Id = id, Name = names[id] }).ToList(),
},
// The game this finishes: a retry can never finish the next game on the court.
GameStartTime = court.LastPlayDate,
});
}
}
Parties récentes
Listez les parties de la dernière semaine avec leurs gagnants.
import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import type { Game } from '@leaguedispatcher/sdk/models';
/** Every game of the last week: the list comes in pages, so send each nextPageToken back until there is none. */
export async function listRecentGames(client: LeagueDispatcherClient): Promise<Game[]> {
const fromDate = Date.now() - 7 * 24 * 60 * 60 * 1000;
const games: Game[] = [];
let pageToken: string | undefined;
do {
const page = await client.games.get({ queryParameters: { fromDate, pageToken } });
games.push(...(page?.games ?? []));
pageToken = page?.nextPageToken ?? undefined;
} while (pageToken);
return games;
}
export async function recentGames(client: LeagueDispatcherClient): Promise<void> {
for (const game of await listRecentGames(client)) {
const ended = new Date(game.endTime ?? 0).toLocaleString();
const winners = (game.winners?.players ?? []).map(p => p.name).join(', ');
console.log(`${ended} ${winners} won ${game.winners?.winnerScore}-${game.winners?.looserScore}`);
}
}
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from kiota_abstractions.base_request_configuration import RequestConfiguration
from leaguedispatcher.games.games_request_builder import GamesRequestBuilder
from leaguedispatcher.league_dispatcher_client import LeagueDispatcherClient
from leaguedispatcher.models.game import Game
async def list_recent_games(client: LeagueDispatcherClient) -> List[Game]:
"""Every game of the last week: the list comes in pages, so send each next_page_token back until there is none."""
from_date = int((datetime.now(timezone.utc) - timedelta(days=7)).timestamp() * 1000)
games: List[Game] = []
page_token: Optional[str] = None
while True:
query = GamesRequestBuilder.GamesRequestBuilderGetQueryParameters(from_date=from_date, page_token=page_token)
page = await client.games.get(RequestConfiguration(query_parameters=query))
games.extend((page.games if page else None) or [])
page_token = page.next_page_token if page else None
if not page_token:
return games
async def recent_games(client: LeagueDispatcherClient) -> None:
for game in await list_recent_games(client):
ended = datetime.fromtimestamp((game.end_time or 0) / 1000).strftime("%Y-%m-%d %H:%M")
winners = game.winners
names = ", ".join(p.name or "" for p in (winners.players if winners else None) or [])
score = f"{winners.winner_score}-{winners.looser_score}" if winners else ""
print(f"{ended} {names} won {score}")
using LeagueDispatcher.Sdk;
using LeagueDispatcher.Sdk.Models;
public static class RecentGames
{
/// <summary>Every game of the last week: the list comes in pages, so send each NextPageToken back until there is none.</summary>
public static async Task<List<Game>> ListAsync(LeagueDispatcherClient client)
{
var fromDate = DateTimeOffset.UtcNow.AddDays(-7).ToUnixTimeMilliseconds();
var games = new List<Game>();
string? pageToken = null;
do
{
var page = await client.Games.GetAsync(config =>
{
config.QueryParameters.FromDate = fromDate;
config.QueryParameters.PageToken = pageToken;
});
games.AddRange(page?.Games ?? []);
pageToken = page?.NextPageToken;
}
while (!string.IsNullOrEmpty(pageToken));
return games;
}
public static async Task RunAsync(LeagueDispatcherClient client)
{
foreach (var game in await ListAsync(client))
{
var ended = DateTimeOffset.FromUnixTimeMilliseconds(game.EndTime ?? 0).LocalDateTime;
var winners = string.Join(", ", game.Winners?.Players?.Select(p => p.Name) ?? []);
Console.WriteLine($"{ended:g} {winners} won {game.Winners?.WinnerScore}-{game.Winners?.LooserScore}");
}
}
}
Recevoir des webhooks
Recevez chaque événement de la ligue sur votre serveur, en direct. Vérifiez la signature avec la bibliothèque officielle Standard Webhooks (ou HMAC-SHA256 en .NET), ignorez les nouvelles tentatives déjà traitées grâce à l'en-tête webhook-id, répondez au défi de vérification avec le WebhookVerificationResponse du SDK, et lisez le corps avec les modèles du SDK : ce sont les mêmes données que les applications reçoivent en direct. Tout y est typé, sans rien à analyser deux fois : actionName indique l'événement, et ses données sont dans leur propre champ (state pour les joueurs et les terrains qui ont changé, y compris une partie terminée ; verification pour le défi ; updatedAt quand des paramètres ont changé). events liste ce qui s'est passé, avec les mêmes enregistrements que l'API des événements. L'exemple .NET montre aussi un contrôleur ASP.NET Core qui décode une partie terminée (score, gagnants et perdants).
// Receives League Dispatcher webhooks: verifies the signature (Standard Webhooks, with the official
// standardwebhooks library), answers the verification challenge, skips retries already handled, and reads the payload
// with the SDK's models. The body is the same payload the app receives live: state events carry the players and courts
// that changed in payload.state.
import http from 'node:http';
import { JsonParseNode, JsonSerializationWriter } from '@microsoft/kiota-serialization-json';
import {
createSignalREventPayloadFromDiscriminatorValue,
serializeWebhookVerificationResponse,
SignalRServerEventObject,
type SignalREventPayload,
type WebhookVerificationResponse,
} from '@leaguedispatcher/sdk/models';
import { Webhook, WebhookVerificationError } from 'standardwebhooks';
export interface WebhookEvent {
payload: SignalREventPayload;
/**
* Set for a WebhookVerification: the JSON body (a WebhookVerificationResponse) to answer with, status 200. The
* endpoint gets no other event until it has answered one.
*/
verificationAnswer?: string;
}
export class WebhookReceiver {
private readonly webhook: Webhook;
// A retry carries the same webhook-id. Keep the ids in a shared store with an expiry when you run several instances.
private readonly seen = new Set<string>();
/** secret: the whsec_... signing secret shown when the webhook was added. */
constructor(secret: string) {
this.webhook = new Webhook(secret);
}
/**
* Returns the event, or null for a retry of an event already received.
* Throws WebhookVerificationError when the request is not a fresh delivery from League Dispatcher.
*/
receive(headers: Record<string, string>, body: string): WebhookEvent | null {
this.webhook.verify(body, headers);
const id = headers['webhook-id'];
if (this.seen.has(id)) return null;
this.seen.add(id);
const payload = new JsonParseNode(JSON.parse(body)).getObjectValue<SignalREventPayload>(createSignalREventPayloadFromDiscriminatorValue);
if (payload.actionName === SignalRServerEventObject.WebhookVerification && payload.verification) {
return { payload, verificationAnswer: verificationAnswer({ challenge: payload.verification.challenge }) };
}
return { payload };
}
}
/** Sends the challenge back, unchanged, as the SDK's WebhookVerificationResponse. */
function verificationAnswer(response: WebhookVerificationResponse): string {
const writer = new JsonSerializationWriter();
writer.writeObjectValue(undefined, response, serializeWebhookVerificationResponse);
return new TextDecoder().decode(writer.getSerializedContent());
}
/**
* A minimal HTTP endpoint: 200 with the answer to a verification, 204 once an event is handled (or a retry), 401 when
* the request is not from League Dispatcher.
*/
export function serve(port: number, secret: string, onEvent: (event: WebhookEvent) => void): http.Server {
const receiver = new WebhookReceiver(secret);
return http.createServer((req, res) => {
let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const event = receiver.receive(req.headers as Record<string, string>, body);
if (event?.verificationAnswer) {
res.writeHead(200, { 'content-type': 'application/json' }).end(event.verificationAnswer);
return;
}
if (event) onEvent(event);
res.writeHead(204).end();
} catch (err) {
res.writeHead(err instanceof WebhookVerificationError ? 401 : 500).end();
}
});
}).listen(port);
}
"""Receives League Dispatcher webhooks: verifies the signature (Standard Webhooks, with the official standardwebhooks
library), answers the verification challenge, skips retries already handled, and reads the payload with the SDK's
models. The body is the same payload the app receives live: state events carry the players and courts that changed in
payload.state.
"""
import json
import threading
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Callable, Mapping, Optional, Set
from kiota_serialization_json.json_parse_node import JsonParseNode
from kiota_serialization_json.json_serialization_writer import JsonSerializationWriter
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
from leaguedispatcher.models.signal_r_event_payload import SignalREventPayload
from leaguedispatcher.models.signal_r_server_event import SignalRServerEvent
from leaguedispatcher.models.webhook_verification_response import WebhookVerificationResponse
@dataclass
class WebhookEvent:
payload: SignalREventPayload
# Set for a WebhookVerification: the JSON body (a WebhookVerificationResponse) to answer with, status 200. The
# endpoint gets no other event until it has answered one.
verification_answer: Optional[bytes] = None
class WebhookReceiver:
def __init__(self, secret: str) -> None:
"""secret: the whsec_... signing secret shown when the webhook was added."""
self._webhook = Webhook(secret)
# A retry carries the same webhook-id. Keep the ids in a shared store with an expiry when you run several
# instances. The lock lets one receiver serve concurrent requests.
self._seen: Set[str] = set()
self._lock = threading.Lock()
def receive(self, headers: Mapping[str, str], body: str) -> Optional[WebhookEvent]:
"""Returns the event, or None for a retry of an event already received.
Raises WebhookVerificationError when the request is not a fresh delivery from League Dispatcher."""
lowered = {key.lower(): value for key, value in headers.items()}
self._webhook.verify(body, lowered)
message_id = lowered["webhook-id"]
with self._lock:
if message_id in self._seen:
return None
self._seen.add(message_id)
payload = JsonParseNode(json.loads(body)).get_object_value(SignalREventPayload)
if payload.action_name == SignalRServerEvent.WebhookVerification and payload.verification:
answer = verification_answer(WebhookVerificationResponse(challenge=payload.verification.challenge))
return WebhookEvent(payload, verification_answer=answer)
return WebhookEvent(payload)
def verification_answer(response: WebhookVerificationResponse) -> bytes:
"""Sends the challenge back, unchanged, as the SDK's WebhookVerificationResponse."""
writer = JsonSerializationWriter()
writer.write_object_value(None, response)
return writer.get_serialized_content()
def serve(port: int, secret: str, on_event: Callable[[WebhookEvent], None]) -> ThreadingHTTPServer:
"""A minimal HTTP endpoint: 200 with the answer to a verification, 204 once an event is handled (or a retry), 401
when the request is not from League Dispatcher."""
receiver = WebhookReceiver(secret)
class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
body = self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode("utf-8")
try:
event = receiver.receive(dict(self.headers.items()), body)
except WebhookVerificationError:
self.send_response(401)
self.end_headers()
return
if event is not None and event.verification_answer is not None:
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(event.verification_answer)))
self.end_headers()
self.wfile.write(event.verification_answer)
return
if event is not None:
on_event(event)
self.send_response(204)
self.end_headers()
return ThreadingHTTPServer(("", port), Handler)
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using LeagueDispatcher.Sdk.Models;
using Microsoft.Kiota.Serialization.Json;
/// <summary>
/// Receives League Dispatcher webhooks: verifies the Standard Webhooks signature (HMAC-SHA256 from System.Security.Cryptography),
/// answers the verification challenge, skips retries already handled, and reads the payload with the SDK's models. The
/// body is the same payload the app receives live: state events carry the players and courts that changed in Payload.State.
/// </summary>
public sealed class WebhookReceiver
{
private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5);
private readonly byte[] _key;
// A retry carries the same webhook-id. Keep the ids in a shared store with an expiry when you run several instances.
// One receiver serves concurrent requests in a web app: the set is guarded by a lock.
private readonly HashSet<string> _seen = [];
/// <param name="secret">The whsec_... signing secret shown when the webhook was added.</param>
public WebhookReceiver(string secret)
{
_key = Convert.FromBase64String(secret.StartsWith("whsec_", StringComparison.Ordinal) ? secret["whsec_".Length..] : secret);
}
/// <param name="Payload">The delivery's body.</param>
/// <param name="VerificationAnswer">
/// Set for a WebhookVerification: the JSON body (a WebhookVerificationResponse) to answer with, status 200. The
/// endpoint gets no other event until it has answered one.
/// </param>
public sealed record WebhookEvent(SignalREventPayload Payload, string? VerificationAnswer = null);
/// <summary>
/// Returns the event, or null for a retry of an event already received.
/// Throws <see cref="WebhookVerificationException"/> when the request is not a fresh delivery from League Dispatcher.
/// </summary>
public WebhookEvent? Receive(IReadOnlyDictionary<string, string> headers, string body)
{
var id = Header(headers, "webhook-id");
var timestamp = Header(headers, "webhook-timestamp");
var signatures = Header(headers, "webhook-signature");
if (!long.TryParse(timestamp, out var seconds)
|| (DateTimeOffset.UtcNow - DateTimeOffset.FromUnixTimeSeconds(seconds)).Duration() > Tolerance)
{
throw new WebhookVerificationException("The delivery is too old or too new.");
}
var expected = HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes($"{id}.{timestamp}.{body}"));
// During a secret rotation the header carries one "v1,<base64>" signature per secret.
var valid = signatures.Split(' ').Any(signature =>
{
var parts = signature.Split(',', 2);
if (parts.Length != 2 || parts[0] != "v1")
{
return false;
}
try
{
return CryptographicOperations.FixedTimeEquals(expected, Convert.FromBase64String(parts[1]));
}
catch (FormatException)
{
return false;
}
});
if (!valid)
{
throw new WebhookVerificationException("The signature does not match.");
}
bool firstTime;
lock (_seen)
{
firstTime = _seen.Add(id);
}
if (!firstTime)
{
return null;
}
var payload = Parse(body, SignalREventPayload.CreateFromDiscriminatorValue);
if (payload.ActionName == SignalRServerEvent.WebhookVerification && payload.Verification is { } verification)
{
return new WebhookEvent(payload, VerificationAnswer(new WebhookVerificationResponse { Challenge = verification.Challenge }));
}
return new WebhookEvent(payload);
}
/// <summary>Sends the challenge back, unchanged, as the SDK's WebhookVerificationResponse.</summary>
private static string VerificationAnswer(WebhookVerificationResponse response)
{
using var writer = new JsonSerializationWriter();
writer.WriteObjectValue(null, response);
using var reader = new StreamReader(writer.GetSerializedContent());
return reader.ReadToEnd();
}
private static T Parse<T>(string json, Microsoft.Kiota.Abstractions.Serialization.ParsableFactory<T> factory)
where T : Microsoft.Kiota.Abstractions.Serialization.IParsable
{
using var document = JsonDocument.Parse(json);
return new JsonParseNode(document.RootElement.Clone()).GetObjectValue(factory)!;
}
private static string Header(IReadOnlyDictionary<string, string> headers, string name) =>
headers.FirstOrDefault(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)).Value
?? throw new WebhookVerificationException($"Missing {name} header.");
}
public sealed class WebhookVerificationException(string message) : Exception(message);
using LeagueDispatcher.Sdk.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
/// <summary>
/// An ASP.NET Core endpoint for League Dispatcher webhooks. Register the receiver once, with the whsec_... secret shown
/// when the webhook was added (WebhookServer.cs):
/// <code>builder.Services.AddSingleton(new WebhookReceiver(builder.Configuration["LeagueDispatcher:WebhookSecret"]!));</code>
/// Answer quickly: a slow or failing answer counts as a failed delivery and is retried.
/// </summary>
[ApiController]
[Route("webhooks/league-dispatcher")]
public class LeagueDispatcherWebhookController(WebhookReceiver receiver, ILogger<LeagueDispatcherWebhookController> logger)
: ControllerBase
{
[HttpPost]
public async Task<IActionResult> Receive()
{
// Verify the raw body: the signature covers these exact bytes, not a re-serialized object.
using var reader = new StreamReader(Request.Body);
var body = await reader.ReadToEndAsync();
var headers = Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString());
WebhookReceiver.WebhookEvent? received;
try
{
received = receiver.Receive(headers, body);
}
catch (WebhookVerificationException ex)
{
logger.LogWarning("Webhook refused: {Reason}", ex.Message);
return Unauthorized();
}
if (received == null)
{
return NoContent(); // A retry of an event already handled.
}
if (received.VerificationAnswer != null)
{
// Sent when the webhook is added (or verified again): no other event arrives until this is answered.
return Content(received.VerificationAnswer, "application/json");
}
if (received.Payload.ActionName == SignalRServerEvent.GameFinished && received.Payload.State?.Game is { } game)
{
var result = FinishedGame.From(game);
logger.LogInformation("Game {GameId} on court {CourtId} finished {WinnerScore}-{LoserScore}: {Winners} beat {Losers}",
result.GameId, result.CourtId, result.WinnerScore, result.LoserScore,
string.Join(" & ", result.Winners), string.Join(" & ", result.Losers));
}
return NoContent();
}
/// <summary>A finished game, decoded from the GameFinished event's State.Game.</summary>
public sealed record FinishedGame(string GameId, string CourtId, int WinnerScore, int LoserScore,
IReadOnlyList<string> Winners, IReadOnlyList<string> Losers, DateTimeOffset? EndedAt)
{
public static FinishedGame From(Game game)
{
var winnerIds = (game.Winners?.Players ?? []).Select(p => p.Id).ToHashSet();
var players = game.Players ?? [];
return new FinishedGame(
game.Id ?? "",
game.CourtId ?? "",
game.Winners?.WinnerScore ?? 0,
game.Winners?.LooserScore ?? 0,
players.Where(p => winnerIds.Contains(p.Id)).Select(p => p.Name ?? p.Id ?? "").ToList(),
players.Where(p => !winnerIds.Contains(p.Id)).Select(p => p.Name ?? p.Id ?? "").ToList(),
game.EndTime is { } end ? DateTimeOffset.FromUnixTimeMilliseconds(end) : null);
}
}
}