fix(andebol): use official FPA name in agenda UI strings (BIT-26494) #29

Merged
spark merged 3 commits from fix/BIT-26494-fpa-federation-name into main 2026-07-13 08:21:21 +01:00
12 changed files with 555 additions and 15 deletions

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 {
+6 -3
View File
@@ -44,7 +44,10 @@ test('getUiStrings en search_results_count', () => {
assert.equal(s.search_results_count(3), '3 results');
});
test('getUiStrings category_meta_latest interpolates name', () => {
const s = getUiStrings('en');
assert.equal(s.category_meta_latest('Handball'), 'Latest Handball news');
test('getUiStrings pt fpa strings use official federation name', () => {
const s = getUiStrings('pt-PT');
assert.ok(s.fpa_agenda_lead.includes('Federação de Andebol de Portugal'));
assert.ok(s.fpa_source_credit.includes('Federação de Andebol de Portugal'));
assert.equal(s.fpa_agenda_lead.includes('Federação Portuguesa de Andebol'), false);
assert.equal(s.fpa_source_credit.includes('Federação Portuguesa de Andebol'), false);
});
+13 -4
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;
@@ -139,16 +142,19 @@ const en: UiStrings = {
explore_sections: 'Explore',
discover_lead: 'Browse by topic or find an article by keyword.',
fpa_agenda_title: 'Upcoming matches',
fpa_agenda_lead: 'National competition fixtures from the Portuguese Handball Federation feed.',
fpa_agenda_lead: 'National competition fixtures (public feed from the Handball Federation of Portugal).',
fpa_col_when: 'When',
fpa_col_match: 'Match',
fpa_col_score: 'Score',
fpa_col_venue: 'Venue',
fpa_col_competition: 'Competition',
fpa_agenda_empty: 'Fixture list is temporarily unavailable.',
fpa_source_credit: 'Data: Portuguese Handball Federation (ws.fpa.pt).',
fpa_source_credit: 'Data: Handball Federation of Portugal (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',
@@ -216,16 +222,19 @@ const pt: UiStrings = {
explore_sections: 'Explorar',
discover_lead: 'Navegue por tema ou encontre um artigo por palavra-chave.',
fpa_agenda_title: 'Próximos jogos',
fpa_agenda_lead: 'Agenda de competições nacionais (feed público da Federação Portuguesa de Andebol).',
fpa_agenda_lead: 'Agenda de competições nacionais (feed público da Federação de Andebol de Portugal).',
fpa_col_when: 'Quando',
fpa_col_match: 'Jogo',
fpa_col_score: 'Resultado',
fpa_col_venue: 'Local',
fpa_col_competition: 'Competição',
fpa_agenda_empty: 'A agenda não está disponível de momento.',
fpa_source_credit: 'Dados: Federação Portuguesa de Andebol (ws.fpa.pt).',
fpa_source_credit: 'Dados: Federação de Andebol de Portugal (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 {
+71 -4
View File
@@ -80,6 +80,62 @@ async function featuredImageFromPageHtml(
return { url: abs, credit: parsed.credit || creditFallback };
}
const IMG_SRC_RE = /<img\s[^>]*src=["']([^"']+)["']/gi;
const IMG_DIMS_RE = /<img\s[^>]*(?:width|height)\s*=\s*["'](\d+)["']/i;
const SKIP_IMG_RE = /(?:\/favicon\.|\/icon[\W-]|tracking|pixel|beacon|spacer|blank|transparent|1x1|\.svg\??|\/tr\?|doubleclick|facebook\.com\/tr|chartbeat|gemius|weborama|analytics|adservice|googlesyndication)/i;
const MIN_DIM_PX = 200;
async function featuredImageFromPageImgs(
pageUrl: string,
creditFallback?: string,
): Promise<{ url: string; credit?: string } | null> {
const raw = await fetchArticleHtmlForMeta(pageUrl);
if (!raw) return null;
const candidates: Array<{ src: string; area: number }> = [];
let m: RegExpExecArray | null;
IMG_SRC_RE.lastIndex = 0;
while ((m = IMG_SRC_RE.exec(raw)) !== null) {
const src = m[1];
if (SKIP_IMG_RE.test(src)) continue;
const abs = absolutizeImageUrl(src, pageUrl);
if (!abs || !allowedMediaUrl(abs)) continue;
if (!/\.(jpe?g|png|webp)(\?|$)/i.test(abs)) continue;
const fullTag = raw.substring(Math.max(0, m.index - 200), m.index + m[0].length + 200);
const dimMatch = fullTag.match(IMG_DIMS_RE);
let area = 1;
if (dimMatch) {
const dim = parseInt(dimMatch[1], 10);
if (dim >= MIN_DIM_PX) area = dim * dim;
else continue;
}
candidates.push({ src: abs, area });
}
candidates.sort((a, b) => b.area - a.area);
for (const c of candidates) {
try {
const res = await fetchBinaryWithRetry(c.src, {
timeoutMs: 10_000,
retries: 1,
userAgent: 'BitReport-news-writer-pipeline/1.0 (featured-image)',
});
if (!res.ok) continue;
const ct = res.headers.get('content-type')?.split(';')[0]?.trim() || '';
if (!ct.startsWith('image/')) continue;
const cl = parseInt(res.headers.get('content-length') || '0', 10);
if (cl > 0 && cl < MIN_DIM_PX * MIN_DIM_PX) continue;
return { url: c.src, credit: creditFallback };
} catch {
continue;
}
}
return null;
}
/**
* Resolves a rights-cleared image URL for the article (ingest hints, then live HTML).
* Throws if none — drafts must not ship without a featured image (BIT-22288).
@@ -89,7 +145,7 @@ export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promis
credit?: string;
/** Sent on GET when the image is not anonymously readable (e.g. WebDAV Basic auth) */
fetchHeaders?: Record<string, string>;
}> {
} | null> {
const fromItem = item.featuredImageUrl?.trim();
if (fromItem && allowedMediaUrl(fromItem)) {
return { url: fromItem, credit: item.featuredImageCredit };
@@ -108,6 +164,9 @@ export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promis
if (publisherHome) {
const fromPublisher = await featuredImageFromPageHtml(publisherHome, item.featuredImageCredit);
if (fromPublisher) return fromPublisher;
const fromPublisherImgs = await featuredImageFromPageImgs(publisherHome, item.featuredImageCredit);
if (fromPublisherImgs) return fromPublisherImgs;
}
}
@@ -117,6 +176,11 @@ export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promis
if (webDavCfg) {
return resolveFeaturedFromWebDavArchive(webDavCfg, item);
}
if (item.sourceKind === 'revista_imprensa') {
return null;
}
if (webDavEnvError) {
throw new Error(
`Mandatory featured image: no og:image / twitter:image (and no RSS image enclosure) for ${item.url}. WebDAV env misconfigured: ${webDavEnvError} (BIT-22292).`,
@@ -271,8 +335,11 @@ export async function createDraftFromAggregatedItem(
const base = cfg.wpBase.replace(/\/$/, '');
const authHeader = `Basic ${basicAuthValue(cfg)}`;
const { url: imageUrl, credit, fetchHeaders } = await resolveFeaturedImageForDraft(item);
const mediaId = await uploadFeaturedMedia(cfg, base, imageUrl, credit, fetchHeaders);
const featured = await resolveFeaturedImageForDraft(item);
let mediaId: number | undefined;
if (featured) {
mediaId = await uploadFeaturedMedia(cfg, base, featured.url, featured.credit, featured.fetchHeaders);
}
const categoryId = await resolveCategoryId(base, authHeader, cfg.siteDomain, categorySlug);
const body: Record<string, unknown> = {
@@ -280,8 +347,8 @@ export async function createDraftFromAggregatedItem(
content: draftContent(item),
status: 'draft',
excerpt: stripTags(item.summary).slice(0, 300),
featured_media: mediaId,
};
if (mediaId) body.featured_media = mediaId;
if (categoryId) body.categories = [categoryId];
const res = await fetch(`${base}/wp/v2/posts`, {