fix(writer-pipeline): allow revista_imprensa drafts without featured image
For revista_imprensa items, the synthetic lead URLs (e.g. /revista-imprensa/DD-MM-YYYY/N) are not real article pages and often return 404. The publisher homepage may also lack og:image (record.pt has empty og:image/twitter:image content attributes). Previously this caused a mandatory featured image error loop. Changes: - resolveFeaturedImageForDraft now returns null instead of throwing for revista_imprensa items when no image is found from any source - Added featuredImageFromPageImgs fallback that scrapes <img> tags from the publisher homepage when og:image is empty/missing, filtering out icons, SVGs, tracking pixels, and small images - createDraftFromAggregatedItem handles null featured image gracefully, creating drafts without featured_media when unavailable BIT-26192 Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1 parent
c1a12cf520
commit
9b6fbe027c
1 file changed
+71
-4
@@ -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`, {
|
||||
|
||||
Reference in new issue
Block a user