feat(andebol): AndebolTV live stream badges on FPA agenda (BIT-26493)
Tests / bridge tests (push) Successful in 37s
Tests / writer-pipeline tests (push) Successful in 39s
Tests / frontend lib tests (push) Successful in 39s

- bridge: andeboltv.ts fetches Pixellot /api/event/list (live + upcoming)
- bridge: fpa-stream-match.ts matches FPA games to AndebolTV streams
- bridge: homepage route enriches agenda with stream_url, stream_status, is_live
- frontend: FpaAgendaSection renders Em direto badge + AndebolTV link
- i18n: PT-PT strings for live/stream status and watch links
- test: fpa-stream-match.test.ts (teams_overlap, teams_match_pair, find, enrich)

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
José AlvesandPaperclip committed 2026-07-13 07:14:35 +00:00
1 parent 9b6fbe027c
commit d057709297
10 files changed
+474 -4

No files matched your search

+7
View File
@@ -21,6 +21,13 @@ RATE_LIMIT_WINDOW_MS=60000
# Log level: fatal | error | warn | info | debug | trace
LOG_LEVEL=info
# AndebolTV / Pixellot OTT — live stream detection for andebol.net agenda (public client key)
# ANDEBOLTV_API_BASE=https://fpa.watch.pixellot.tv
# ANDEBOLTV_PORTAL_URL=https://andeboltv.fpa.pt
# ANDEBOLTV_API_KEY=
# ANDEBOLTV_FETCH_TIMEOUT_MS=15000
# ANDEBOLTV_LIST_SIZE=48
# Error hub ingest (errors.bitreport.pt) — vault only; leave empty in Git examples
# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
# ERROR_REPORTING_TOKEN=
+2 -2
View File
@@ -9,8 +9,8 @@
"build": "tsc",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit",
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js",
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js"
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/fpa-stream-match.test.js",
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/fpa-stream-match.test.js"
},
"dependencies": {
"@fastify/cors": "^9.0.1",
+15 -1
View File
@@ -4,7 +4,10 @@ import { resolve_site_host } from '../lib/request-host.js';
import { WpClient } from '../services/wp-client.js';
import { swr_fetch } from '../services/cache.js';
import type { ArticleListItem, FpaAgendaGame, HomepageData } from '../types.js';
import type { AndebolTvStreamEvent } from '../services/andeboltv.js';
import { fetch_andeboltv_stream_events } from '../services/andeboltv.js';
import { fetch_fpa_agenda } from '../services/fpa-agenda.js';
import { enrich_fpa_agenda_with_streams } from '../services/fpa-stream-match.js';
// Number of articles per section
const HERO_COUNT = 3;
@@ -137,7 +140,18 @@ export async function homepage_routes(app: FastifyInstance): Promise<void> {
const fpa_agenda: FpaAgendaGame[] | null = config.fpa_agenda_enabled
? await swr_fetch<FpaAgendaGame[]>(`${host}:fpa:agenda`, async () => {
try {
return await fetch_fpa_agenda();
const [games, streams] = await Promise.all([
fetch_fpa_agenda(),
swr_fetch<AndebolTvStreamEvent[]>(`${host}:andeboltv:streams`, async () => {
try {
return await fetch_andeboltv_stream_events();
} catch (err) {
app.log.warn({ err, host }, 'AndebolTV stream fetch failed');
return [];
}
}),
]);
return enrich_fpa_agenda_with_streams(games, streams);
} catch (err) {
app.log.warn({ err, host }, 'FPA agenda fetch failed');
return [];
+160
View File
@@ -0,0 +1,160 @@
/** AndebolTV (Pixellot OTT) public event feed — powers live/upcoming stream badges on andebol.net. */
const ANDEBOLTV_API_BASE =
process.env['ANDEBOLTV_API_BASE'] ?? 'https://fpa.watch.pixellot.tv';
const ANDEBOLTV_PORTAL_URL =
process.env['ANDEBOLTV_PORTAL_URL'] ?? 'https://andeboltv.fpa.pt';
/** Public client segment key (also embedded in andeboltv.fpa.pt SPA config). */
const ANDEBOLTV_API_KEY =
process.env['ANDEBOLTV_API_KEY'] ?? 'TTwNPGgGq87Enc7FJOT7a09ow705dQPk';
const FETCH_TIMEOUT_MS = parseInt(process.env['ANDEBOLTV_FETCH_TIMEOUT_MS'] ?? '15000', 10);
const LIST_PAGE_SIZE = Math.min(parseInt(process.env['ANDEBOLTV_LIST_SIZE'] ?? '48', 10), 100);
export type AndebolTvEventStatus = 'live' | 'upcoming';
export interface AndebolTvStreamEvent {
reference_id: string;
event_id: string;
home_team: string;
away_team: string;
/** ISO date `YYYY-MM-DD` in Europe/Lisbon calendar day. */
date: string;
status: AndebolTvEventStatus;
stream_url: string;
}
interface PixellotTeam {
name?: string;
}
interface PixellotEventTeams {
homeTeam?: PixellotTeam;
awayTeam?: PixellotTeam;
}
interface PixellotListEntry {
_id?: string;
event_id?: string;
reference_id?: string;
event_date?: number;
gameStartDate?: number;
status?: string;
eventTeams?: PixellotEventTeams;
}
interface PixellotListResponse {
content?: {
entries?: PixellotListEntry[];
};
error?: boolean;
}
function as_trimmed_string(value: unknown): string {
if (value === null || value === undefined) {
return '';
}
return String(value).trim();
}
/** Map Pixellot epoch-ms to `YYYY-MM-DD` in Lisbon. */
export function pixellot_ms_to_lisbon_date(ms: number): string {
return new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Lisbon',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date(ms));
}
function build_stream_url(reference_id: string): string {
const base = ANDEBOLTV_PORTAL_URL.replace(/\/$/, '');
return `${base}/events/${encodeURIComponent(reference_id)}`;
}
function parse_entry(entry: PixellotListEntry, status: AndebolTvEventStatus): AndebolTvStreamEvent | null {
const reference_id = as_trimmed_string(entry.reference_id);
const event_id = as_trimmed_string(entry.event_id ?? entry._id);
const home_team = as_trimmed_string(entry.eventTeams?.homeTeam?.name);
const away_team = as_trimmed_string(entry.eventTeams?.awayTeam?.name);
const event_ms = entry.gameStartDate ?? entry.event_date;
if (!reference_id || !event_id || !home_team || !away_team || !event_ms) {
return null;
}
return {
reference_id,
event_id,
home_team,
away_team,
date: pixellot_ms_to_lisbon_date(event_ms),
status,
stream_url: build_stream_url(reference_id),
};
}
async function fetch_status_list(status: AndebolTvEventStatus): Promise<AndebolTvStreamEvent[]> {
const res = await fetch(`${ANDEBOLTV_API_BASE}/api/event/list`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'x-api-key': ANDEBOLTV_API_KEY,
},
body: JSON.stringify({
page: 0,
size: LIST_PAGE_SIZE,
filters: {
sportType: 'handball',
status,
},
}),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
throw new Error(`AndebolTV list HTTP ${res.status} (${status})`);
}
const raw = (await res.json()) as PixellotListResponse;
if (raw.error) {
throw new Error(`AndebolTV list error (${status})`);
}
const entries = raw.content?.entries ?? [];
const out: AndebolTvStreamEvent[] = [];
for (const entry of entries) {
const parsed = parse_entry(entry, status);
if (parsed) {
out.push(parsed);
}
}
return out;
}
/**
* Fetch handball events with AndebolTV streams (live + upcoming).
* Deduplicates by `reference_id`, preferring `live` over `upcoming`.
*/
export async function fetch_andeboltv_stream_events(): Promise<AndebolTvStreamEvent[]> {
const [live, upcoming] = await Promise.all([
fetch_status_list('live'),
fetch_status_list('upcoming'),
]);
const by_ref = new Map<string, AndebolTvStreamEvent>();
for (const event of upcoming) {
by_ref.set(event.reference_id, event);
}
for (const event of live) {
by_ref.set(event.reference_id, event);
}
return [...by_ref.values()];
}
@@ -0,0 +1,88 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
enrich_fpa_agenda_with_streams,
find_stream_for_game,
teams_match_pair,
teams_overlap,
} from './fpa-stream-match.js';
import type { AndebolTvStreamEvent } from './andeboltv.js';
import type { FpaAgendaGame } from '../types.js';
test('teams_overlap matches national team shorthand', () => {
assert.equal(teams_overlap('PORTUGAL', 'Portugal M18'), true);
assert.equal(teams_overlap('ALEMANHA', 'Germany M18'), true);
});
test('teams_match_pair accepts swapped home/away', () => {
assert.equal(teams_match_pair('Benfica', 'Porto', 'FC Porto', 'SL Benfica'), true);
});
test('find_stream_for_game matches by date and team names', () => {
const game: FpaAgendaGame = {
match_id: '1',
date: '2026-07-17',
time: '19:00',
home_team: 'PORTUGAL',
away_team: 'ALEMANHA',
home_goals: null,
away_goals: null,
venue: 'Maia',
competition: 'Seleções',
phase: 'Sub-18',
home_logo_url: null,
away_logo_url: null,
};
const streams: AndebolTvStreamEvent[] = [
{
reference_id: 'abc',
event_id: 'abc',
home_team: 'Portugal M18',
away_team: 'Germany M18',
date: '2026-07-17',
status: 'upcoming',
stream_url: 'https://andeboltv.fpa.pt/events/abc',
},
];
const match = find_stream_for_game(game, streams);
assert.ok(match);
assert.equal(match?.stream_url, 'https://andeboltv.fpa.pt/events/abc');
});
test('enrich_fpa_agenda_with_streams adds stream fields', () => {
const games: FpaAgendaGame[] = [
{
match_id: '1',
date: '2026-07-17',
time: '19:00',
home_team: 'PORTUGAL',
away_team: 'ALEMANHA',
home_goals: null,
away_goals: null,
venue: 'Maia',
competition: 'Seleções',
phase: '',
home_logo_url: null,
away_logo_url: null,
},
];
const streams: AndebolTvStreamEvent[] = [
{
reference_id: 'live1',
event_id: 'live1',
home_team: 'Portugal M18',
away_team: 'Germany M18',
date: '2026-07-17',
status: 'live',
stream_url: 'https://andeboltv.fpa.pt/events/live1',
},
];
const enriched = enrich_fpa_agenda_with_streams(games, streams);
assert.equal(enriched[0]?.is_live, true);
assert.equal(enriched[0]?.stream_status, 'live');
assert.equal(enriched[0]?.stream_url, 'https://andeboltv.fpa.pt/events/live1');
});
+130
View File
@@ -0,0 +1,130 @@
import type { AndebolTvStreamEvent } from './andeboltv.js';
import type { FpaAgendaGame } from '../types.js';
/** PT (FPA feed) ↔ EN (AndebolTV/Pixellot) aliases for national/club name matching. */
const TEAM_ALIAS_GROUPS: string[][] = [
['portugal', 'por'],
['alemanha', 'germany', 'ger', 'deutschland'],
['franca', 'france', 'fra'],
['espanha', 'spain', 'esp'],
['italia', 'italy', 'ita'],
['holanda', 'netherlands', 'ned', 'hol'],
['suecia', 'sweden', 'swe'],
['noruega', 'norway', 'nor'],
['dinamarca', 'denmark', 'den'],
['islandia', 'iceland', 'isl'],
['polonia', 'poland', 'pol'],
['croacia', 'croatia', 'cro'],
['servia', 'serbia', 'srb'],
['eslovenia', 'slovenia', 'svn'],
['hungria', 'hungary', 'hun'],
['romenia', 'romania', 'rou'],
['grecia', 'greece', 'gre'],
['angola'],
['brasil', 'brazil', 'bra'],
];
function normalize_team_token(value: string): string {
return value
.normalize('NFD')
.replace(/\p{M}/gu, '')
.toLowerCase()
.replace(/\b(fc|sc|ad|cp|gd|cd|aa|hb|sl)\b/g, ' ')
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}
function team_tokens(name: string): string[] {
const normalized = normalize_team_token(name);
if (!normalized) {
return [];
}
const tokens = normalized.split(/\s+/).filter((t) => t.length >= 2);
return tokens.length > 0 ? tokens : [normalized];
}
function canonical_team_keys(name: string): Set<string> {
const keys = new Set<string>();
const compact = normalize_team_token(name).replace(/\s+/g, '');
if (compact) {
keys.add(compact);
}
for (const token of team_tokens(name)) {
keys.add(token);
for (const group of TEAM_ALIAS_GROUPS) {
if (group.some((alias) => token.includes(alias) || alias.includes(token))) {
for (const alias of group) {
keys.add(alias);
}
}
}
}
return keys;
}
/** True when team names refer to the same side (fuzzy PT/EN + token overlap). */
export function teams_overlap(a: string, b: string): boolean {
const keys_a = canonical_team_keys(a);
const keys_b = canonical_team_keys(b);
if (keys_a.size === 0 || keys_b.size === 0) {
return false;
}
for (const key of keys_a) {
if (keys_b.has(key)) {
return true;
}
for (const other of keys_b) {
if (key.length >= 4 && (other.includes(key) || key.includes(other))) {
return true;
}
}
}
return false;
}
export function teams_match_pair(
home_a: string,
away_a: string,
home_b: string,
away_b: string,
): boolean {
const direct = teams_overlap(home_a, home_b) && teams_overlap(away_a, away_b);
const swapped = teams_overlap(home_a, away_b) && teams_overlap(away_a, home_b);
return direct || swapped;
}
export function find_stream_for_game(
game: FpaAgendaGame,
streams: AndebolTvStreamEvent[],
): AndebolTvStreamEvent | null {
const candidates = streams.filter((s) => s.date === game.date);
for (const stream of candidates) {
if (teams_match_pair(game.home_team, game.away_team, stream.home_team, stream.away_team)) {
return stream;
}
}
return null;
}
export function enrich_fpa_agenda_with_streams(
games: FpaAgendaGame[],
streams: AndebolTvStreamEvent[],
): FpaAgendaGame[] {
if (streams.length === 0) {
return games;
}
return games.map((game) => {
const stream = find_stream_for_game(game, streams);
if (!stream) {
return game;
}
return {
...game,
stream_url: stream.stream_url,
stream_status: stream.status,
is_live: stream.status === 'live',
};
});
}
+6
View File
@@ -34,6 +34,12 @@ export interface FpaAgendaGame {
/** Club emblem from FPA `getClube` (si.fpa.pt); null when unavailable. */
home_logo_url: string | null;
away_logo_url: string | null;
/** AndebolTV stream page when matched from andeboltv.fpa.pt (Pixellot). */
stream_url?: string | null;
/** `live` or `upcoming` from AndebolTV; omitted when no stream. */
stream_status?: 'live' | 'upcoming' | null;
/** Convenience flag when `stream_status === 'live'`. */
is_live?: boolean;
}
export interface CategoryConfig {
+9
View File
@@ -57,6 +57,9 @@ export type UiStrings = {
fpa_source_credit: string;
fpa_status_finished: string;
fpa_status_upcoming: string;
fpa_status_live: string;
fpa_watch_live: string;
fpa_watch_stream: string;
fpa_games_on_date: (count: number) => string;
/** News archive page title */
news_archive_title: string;
@@ -149,6 +152,9 @@ const en: UiStrings = {
fpa_source_credit: 'Data: Portuguese Handball Federation (ws.fpa.pt).',
fpa_status_finished: 'FT',
fpa_status_upcoming: 'Upcoming',
fpa_status_live: 'Live',
fpa_watch_live: 'Watch live',
fpa_watch_stream: 'Watch on AndebolTV',
fpa_games_on_date: count => (count === 1 ? '1 match' : `${count} matches`),
news_archive_title: 'News',
news_all_filter: 'All',
@@ -226,6 +232,9 @@ const pt: UiStrings = {
fpa_source_credit: 'Dados: Federação Portuguesa de Andebol (ws.fpa.pt).',
fpa_status_finished: 'Fim',
fpa_status_upcoming: 'Por jogar',
fpa_status_live: 'Em direto',
fpa_watch_live: 'Ver em direto',
fpa_watch_stream: 'Ver na AndebolTV',
fpa_games_on_date: count => (count === 1 ? '1 jogo' : `${count} jogos`),
news_archive_title: 'Notícias',
news_all_filter: 'Todas',
@@ -69,6 +69,13 @@ const date_groups = [...by_date.entries()];
{day_games.map((g) => {
const finished = is_finished(g);
const score = format_score(g);
const has_stream = Boolean(g.stream_url);
const is_live = Boolean(g.is_live);
const status_label = finished
? ui.fpa_status_finished
: is_live
? ui.fpa_status_live
: ui.fpa_status_upcoming;
return (
<li class="fpa-agenda__card" role="listitem">
<article class="fpa-agenda__match">
@@ -79,9 +86,11 @@ const date_groups = [...by_date.entries()];
class:list={[
'fpa-agenda__status',
finished && 'fpa-agenda__status--finished',
is_live && 'fpa-agenda__status--live',
has_stream && !is_live && !finished && 'fpa-agenda__status--stream',
]}
>
{finished ? ui.fpa_status_finished : ui.fpa_status_upcoming}
{status_label}
</span>
</header>
@@ -164,6 +173,16 @@ const date_groups = [...by_date.entries()];
<span>{g.venue}</span>
</span>
)}
{has_stream && (
<a
class="fpa-agenda__stream-link"
href={g.stream_url!}
target="_blank"
rel="noopener noreferrer"
>
{is_live ? ui.fpa_watch_live : ui.fpa_watch_stream}
</a>
)}
</footer>
</article>
</li>
@@ -410,6 +429,24 @@ const date_groups = [...by_date.entries()];
border-color: color-mix(in srgb, var(--color-primary) 22%, transparent);
}
.fpa-agenda__status--live {
background: #d22018;
color: #fff;
border-color: #d22018;
animation: fpa-live-pulse 2s ease-in-out infinite;
}
.fpa-agenda__status--stream {
background: color-mix(in srgb, #a20c17 14%, var(--color-bg-card));
color: #a20c17;
border-color: color-mix(in srgb, #a20c17 28%, transparent);
}
@keyframes fpa-live-pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.78; }
}
.fpa-agenda__faceoff {
display: grid;
grid-template-columns: 1fr auto 1fr;
@@ -556,6 +593,19 @@ const date_groups = [...by_date.entries()];
opacity: 0.7;
}
.fpa-agenda__stream-link {
margin-left: auto;
font-size: 0.8125rem;
font-weight: 700;
color: #a20c17;
text-decoration: none;
white-space: nowrap;
}
.fpa-agenda__stream-link:hover {
text-decoration: underline;
}
.fpa-agenda__credit {
margin: var(--space-6) 0 0;
font-size: var(--text-xs);
+6
View File
@@ -49,6 +49,12 @@ export interface FpaAgendaGame {
/** Club emblem from FPA `getClube` (si.fpa.pt); null when unavailable. */
home_logo_url?: string | null;
away_logo_url?: string | null;
/** AndebolTV stream page when matched from andeboltv.fpa.pt (Pixellot). */
stream_url?: string | null;
/** `live` or `upcoming` from AndebolTV; omitted when no stream. */
stream_status?: 'live' | 'upcoming' | null;
/** Convenience flag when `stream_status === 'live'`. */
is_live?: boolean;
}
export interface Article {