Harden Meta publish against dirty captions and IG duplicates.

Strip production notes before posting, persist each network id immediately, refuse IG republish if delete fails, and place FB photos via feed for better timeline visibility.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-10-08 17:17:07 +02:00
parent 67969b12cb
commit 025fc85175
6 changed files with 368 additions and 120 deletions

View File

@@ -9,6 +9,7 @@ import {
normalizeChannels,
type PublishChannel,
} from '@/lib/pipeline-schedule';
import { sanitizePublishCaption } from '@/lib/publish-caption';
const META = 'https://graph.facebook.com/v21.0';
@@ -41,6 +42,9 @@ export type PublishResult = {
fbPermalink?: string | null;
error?: string;
channels: PublishChannel[];
/** Caption actually sent to Meta (production noise stripped). */
sanitizedCaption?: string | null;
captionStripped?: string[];
};
type GraphJson = Record<string, unknown>;
@@ -376,12 +380,17 @@ async function waitIgContainer(
return { ok: false, error: 'Timeout esperando contenedor IG' };
}
function publicCaption(item: PipelinePublishRow, maxLen = 2200): string {
const raw = item.caption || item.title || '';
return sanitizePublishCaption(raw, { maxLen }).caption || (item.title || '').slice(0, maxLen);
}
async function publishIgMedia(
igUserId: string,
pageToken: string,
item: PipelinePublishRow
): Promise<{ id: string | null; permalink: string | null; error?: string }> {
const caption = (item.caption || item.title || '').slice(0, 2200);
const caption = publicCaption(item, 2200);
const format = (item.format || 'post').toLowerCase();
const slides = slidePathsOf(item.slide_paths);
const cover = item.cover_path || slides[0] || null;
@@ -503,12 +512,49 @@ async function publishIgMedia(
return { id: mediaId, permalink };
}
async function publishFbFeedWithPhotos(
pageId: string,
pageToken: string,
message: string,
photoIds: string[]
): Promise<{ id: string | null; permalink: string | null; error?: string }> {
if (!photoIds.length) {
return { id: null, permalink: null, error: 'Sin fotos para el feed FB' };
}
const form = new URLSearchParams({
message,
access_token: pageToken,
});
photoIds.forEach((id, i) => {
form.append(`attached_media[${i}]`, JSON.stringify({ media_fbid: id }));
});
const r = await fetch(`${META}/${encodeURIComponent(pageId)}/feed`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form.toString(),
cache: 'no-store',
});
const raw = await r.text();
let json: GraphJson = {};
try {
json = JSON.parse(raw) as GraphJson;
} catch {
/* */
}
if (!r.ok || typeof json.id !== 'string') {
return { id: null, permalink: null, error: formatGraphError(raw) };
}
return { id: json.id, permalink: null };
}
async function publishFbPost(
pageId: string,
pageToken: string,
item: PipelinePublishRow
): Promise<{ id: string | null; permalink: string | null; error?: string }> {
const message = (item.caption || item.title || '').slice(0, 6000);
// Prefer /feed + unpublished photos so the post lands on the Page timeline
// (direct /photos published=true often only shows in Fotos, not on top).
const message = publicCaption(item, 6000);
const format = (item.format || 'post').toLowerCase();
const slides = slidePathsOf(item.slide_paths);
const cover = item.cover_path || slides[0] || null;
@@ -540,68 +586,33 @@ async function publishFbPost(
return { id: vid.json.id, permalink: null };
}
if (format === 'carrusel') {
const paths = [cover, ...slides.filter((p) => p !== cover)].slice(0, 10);
const mediaIds: string[] = [];
for (const path of paths) {
const url = await signedAssetUrl(path);
if (!url) continue;
const ph = await graphPost(`${encodeURIComponent(pageId)}/photos`, pageToken, {
url,
published: 'false',
});
if (ph.ok && typeof ph.json.id === 'string') {
mediaIds.push(ph.json.id);
}
}
if (mediaIds.length >= 2) {
const form = new URLSearchParams({
message,
access_token: pageToken,
});
mediaIds.forEach((id, i) => {
form.append(`attached_media[${i}]`, JSON.stringify({ media_fbid: id }));
});
const r = await fetch(`${META}/${encodeURIComponent(pageId)}/feed`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form.toString(),
cache: 'no-store',
});
const raw = await r.text();
let json: GraphJson = {};
try {
json = JSON.parse(raw) as GraphJson;
} catch {
/* */
}
if (!r.ok || typeof json.id !== 'string') {
return { id: null, permalink: null, error: formatGraphError(raw) };
}
return { id: json.id, permalink: null };
const paths =
format === 'carrusel'
? [cover, ...slides.filter((p) => p !== cover)].slice(0, 10)
: [cover];
const mediaIds: string[] = [];
for (const path of paths) {
const url = await signedAssetUrl(path);
if (!url) continue;
const ph = await graphPost(`${encodeURIComponent(pageId)}/photos`, pageToken, {
url,
published: 'false',
});
if (ph.ok && typeof ph.json.id === 'string') {
mediaIds.push(ph.json.id);
}
}
const url = await signedAssetUrl(cover);
if (!url) {
if (format === 'carrusel' && mediaIds.length < 2) {
return {
id: null,
permalink: null,
error: 'Carrusel FB necesita al menos 2 imágenes',
};
}
if (!mediaIds.length) {
return { id: null, permalink: null, error: 'No URL firmada FB imagen' };
}
const photo = await graphPost(`${encodeURIComponent(pageId)}/photos`, pageToken, {
url,
caption: message,
published: 'true',
});
if (
!photo.ok ||
(typeof photo.json.id !== 'string' && typeof photo.json.post_id !== 'string')
) {
return { id: null, permalink: null, error: formatGraphError(photo.raw) };
}
const id =
(typeof photo.json.post_id === 'string' && photo.json.post_id) ||
(typeof photo.json.id === 'string' && photo.json.id) ||
null;
return { id, permalink: null };
return publishFbFeedWithPhotos(pageId, pageToken, message, mediaIds);
}
export async function publishPipelineItem(
@@ -609,9 +620,22 @@ export async function publishPipelineItem(
opts?: { forceIg?: boolean; forceFb?: boolean; skipIg?: boolean; skipFb?: boolean }
): Promise<PublishResult> {
const channels = normalizeChannels(item.channels);
const scrub = sanitizePublishCaption(item.caption || item.title || '', {
maxLen: 6000,
});
const cleanItem: PipelinePublishRow = {
...item,
caption: scrub.caption || item.title || '',
};
const resolved = await resolveTenantMetaTargets(item.tenant_id);
if (!resolved.targets) {
return { ok: false, error: resolved.error, channels };
return {
ok: false,
error: resolved.error,
channels,
sanitizedCaption: scrub.caption,
captionStripped: scrub.stripped,
};
}
const { pageId, igUserId, pageToken } = resolved.targets;
@@ -628,7 +652,7 @@ export async function publishPipelineItem(
if (!igUserId) {
errors.push('Sin Instagram Business vinculado a la Página');
} else if (!igMediaId) {
const ig = await publishIgMedia(igUserId, pageToken, item);
const ig = await publishIgMedia(igUserId, pageToken, cleanItem);
if (ig.error || !ig.id) {
errors.push(`IG: ${ig.error || 'fallo'}`);
} else {
@@ -640,7 +664,7 @@ export async function publishPipelineItem(
if (wantFb) {
if (!fbPostId) {
const fb = await publishFbPost(pageId, pageToken, item);
const fb = await publishFbPost(pageId, pageToken, cleanItem);
if (fb.error || !fb.id) {
errors.push(`FB: ${fb.error || 'fallo'}`);
} else {
@@ -662,6 +686,8 @@ export async function publishPipelineItem(
fbPermalink,
error: errors.length ? errors.join(' · ') : undefined,
channels,
sanitizedCaption: scrub.caption,
captionStripped: scrub.stripped,
};
}
@@ -808,9 +834,16 @@ export async function updateLivePipelineItem(
return { ok: false, error: resolved.error };
}
const { pageId, igUserId, pageToken } = resolved.targets;
const caption = (item.caption || item.title || '').slice(0, 2200);
const scrub = sanitizePublishCaption(item.caption || item.title || '', {
maxLen: 2200,
});
const caption = scrub.caption || (item.title || '').slice(0, 2200);
const cleanItem: PipelinePublishRow = { ...item, caption };
const notes: string[] = [];
const errors: string[] = [];
if (scrub.stripped.length) {
notes.push(`Copy: quitadas ${scrub.stripped.length} notas internas`);
}
let igMediaId: string | null = item.meta_ig_media_id || null;
let fbPostId: string | null = item.meta_fb_post_id || null;
@@ -830,7 +863,7 @@ export async function updateLivePipelineItem(
errors.push(`FB edit: ${formatGraphError(edit.raw)}`);
} else {
const pub = await publishFbPost(pageId, pageToken, {
...item,
...cleanItem,
meta_fb_post_id: null,
});
if (!pub.id) {
@@ -843,7 +876,7 @@ export async function updateLivePipelineItem(
}
}
} else if (channels.includes('facebook') && !fbPostId) {
const pub = await publishFbPost(pageId, pageToken, item);
const pub = await publishFbPost(pageId, pageToken, cleanItem);
if (!pub.id) errors.push(`FB: ${pub.error || 'fallo'}`);
else {
fbPostId = pub.id;
@@ -851,32 +884,40 @@ export async function updateLivePipelineItem(
}
}
// Instagram: must delete + republish
// Instagram: must delete + republish — never publish a second copy if delete fails.
if (channels.includes('instagram')) {
if (!igUserId) {
errors.push('Sin Instagram Business vinculado');
} else {
let canRepublish = true;
if (igMediaId) {
const d = await graphDelete(encodeURIComponent(igMediaId), pageToken);
if (
!d.ok &&
!formatGraphError(d.raw).toLowerCase().includes('does not exist') &&
!formatGraphError(d.raw).toLowerCase().includes('unsupported')
) {
errors.push(`IG borrar: ${formatGraphError(d.raw)}`);
const gone =
d.ok ||
formatGraphError(d.raw).toLowerCase().includes('does not exist') ||
formatGraphError(d.raw).toLowerCase().includes('unsupported') ||
formatGraphError(d.raw).toLowerCase().includes('no existe');
if (!gone) {
errors.push(
`IG borrar: ${formatGraphError(d.raw)} (no se republica para evitar duplicado)`
);
canRepublish = false;
} else {
igMediaId = null;
}
igMediaId = null;
}
const pub = await publishIgMedia(igUserId, pageToken, {
...item,
meta_ig_media_id: null,
});
if (!pub.id) {
errors.push(`IG republicar: ${pub.error || 'fallo'}`);
} else {
igMediaId = pub.id;
igPermalink = pub.permalink;
notes.push('IG: republicado con nuevo copy');
if (canRepublish) {
const pub = await publishIgMedia(igUserId, pageToken, {
...cleanItem,
meta_ig_media_id: null,
});
if (!pub.id) {
errors.push(`IG republicar: ${pub.error || 'fallo'}`);
} else {
igMediaId = pub.id;
igPermalink = pub.permalink;
notes.push('IG: republicado con nuevo copy');
}
}
}
}

View File

@@ -8,6 +8,8 @@ import {
publishPipelineItem,
type PipelinePublishRow,
} from '@/lib/meta-publish';
import { normalizeChannels } from '@/lib/pipeline-schedule';
import { sanitizePublishCaption } from '@/lib/publish-caption';
const SELECT =
'id,tenant_id,title,format,status,scheduled_at,channels,publish_status,publish_attempts,cover_path,cover_mime,slide_paths,caption,notes,meta_ig_media_id,meta_fb_post_id,updated_at';
@@ -156,7 +158,8 @@ export async function processDuePipelinePublishes(opts?: {
const results: DuePublishResult[] = [];
for (const item of slice) {
for (const due of slice) {
let item: typeof due = due;
const attempts = (item.publish_attempts || 0) + 1;
const lock = await patchItem(base, headers, item.id, {
publish_status: 'publishing',
@@ -174,42 +177,103 @@ export async function processDuePipelinePublishes(opts?: {
continue;
}
const result = await publishPipelineItem(item);
if (!result.ok) {
// Sanitize + persist clean caption before hitting Meta.
const scrub = sanitizePublishCaption(item.caption || item.title || '', {
maxLen: 6000,
});
const cleanCaption = scrub.caption || item.title || '';
if (scrub.changed && cleanCaption !== (item.caption || '')) {
await patchItem(base, headers, item.id, { caption: cleanCaption || null });
item = { ...item, caption: cleanCaption };
}
// Publish IG then FB in two steps, persisting each Meta id immediately
// so a crash / FB failure cannot create a duplicate IG on retry.
const channels = normalizeChannels(item.channels);
const errors: string[] = [];
let igMediaId: string | null = item.meta_ig_media_id || null;
let fbPostId: string | null = item.meta_fb_post_id || null;
let igPermalink: string | null = null;
let fbPermalink: string | null = null;
if (channels.includes('instagram') && !igMediaId) {
const ig = await publishPipelineItem(item, { skipFb: true });
if (ig.sanitizedCaption && ig.sanitizedCaption !== (item.caption || '')) {
await patchItem(base, headers, item.id, {
caption: ig.sanitizedCaption,
});
item = { ...item, caption: ig.sanitizedCaption };
}
if (ig.igMediaId) {
igMediaId = ig.igMediaId;
igPermalink = ig.igPermalink || null;
await patchItem(base, headers, item.id, {
meta_ig_media_id: igMediaId,
});
item = { ...item, meta_ig_media_id: igMediaId };
}
if (!ig.ok) {
errors.push(ig.error || 'IG falló');
}
}
if (channels.includes('facebook') && !fbPostId && errors.length === 0) {
const fb = await publishPipelineItem(
{ ...item, meta_ig_media_id: igMediaId },
{ skipIg: true }
);
if (fb.fbPostId) {
fbPostId = fb.fbPostId;
fbPermalink = fb.fbPermalink || null;
await patchItem(base, headers, item.id, {
meta_fb_post_id: fbPostId,
});
item = { ...item, meta_fb_post_id: fbPostId };
}
if (!fb.ok) {
errors.push(fb.error || 'FB falló');
}
}
const wantIg = channels.includes('instagram');
const wantFb = channels.includes('facebook');
const igOk = !wantIg || Boolean(igMediaId);
const fbOk = !wantFb || Boolean(fbPostId);
const ok = igOk && fbOk && errors.length === 0;
if (!ok) {
await patchItem(base, headers, item.id, {
publish_status: 'failed',
publish_error: result.error || 'Error Meta',
meta_ig_media_id: result.igMediaId || item.meta_ig_media_id || null,
meta_fb_post_id: result.fbPostId || item.meta_fb_post_id || null,
publish_error: errors.join(' · ') || 'Error Meta',
meta_ig_media_id: igMediaId,
meta_fb_post_id: fbPostId,
caption: cleanCaption || null,
});
results.push({
id: item.id,
title: item.title,
ok: false,
detail: result.error || 'publish failed',
detail: errors.join(' · ') || 'publish failed',
});
continue;
}
const notes = mergePermalinkNotes(
item.notes,
result.igPermalink,
result.fbPermalink
);
const notes = mergePermalinkNotes(item.notes, igPermalink, fbPermalink);
await patchItem(base, headers, item.id, {
publish_status: 'published',
publish_error: null,
published_at: new Date().toISOString(),
status: 'publicado',
meta_ig_media_id: result.igMediaId || null,
meta_fb_post_id: result.fbPostId || null,
meta_ig_media_id: igMediaId,
meta_fb_post_id: fbPostId,
caption: cleanCaption || null,
notes,
});
results.push({
id: item.id,
title: item.title,
ok: true,
detail: `published ig=${result.igMediaId || '-'} fb=${result.fbPostId || '-'}`,
detail: `published ig=${igMediaId || '-'} fb=${fbPostId || '-'}`,
});
}

View File

@@ -0,0 +1,76 @@
/**
* Sanitize captions before Meta publish.
* Strips internal production notes that sometimes get pasted from
* briefings / Excel / WhatsApp (filenames, status, assignee).
*/
const FILE_NAME_LINE =
/^(?:whatsapp\s+image|img|image|foto|captura|screenshot|screen\s*shot)[\s_\-.].*$/i;
const EXT_FILE_LINE =
/^[\w.\- ()]+\.(?:jpe?g|png|heic|webp|mov|mp4|pdf)$/i;
const STATUS_LINE =
/^(?:pendiente(?:\s+publicar)?|para\s+publicar|en\s+proceso|borrador|draft|to\s+publish|ready\s+to\s+post|en\s+feedback|link\s+pieza(?:\s+en\s+alta)?|copy\s*:?|fecha\s+de\s+publicaci[oó]n\s*:.*)$/i;
/** Lone "Name Surname." / "Name Surname" production assignee lines */
const ASSIGNEE_LINE = /^[A-ZÁÉÍÓÚÑ][a-záéíóúñ]+(?:\s+[A-ZÁÉÍÓÚÑ][a-záéíóúñ]+){1,3}\.?$/;
export type CaptionSanitizeResult = {
caption: string;
stripped: string[];
changed: boolean;
};
export function looksLikeProductionNoise(line: string): boolean {
const t = line.trim();
if (!t) return false;
if (FILE_NAME_LINE.test(t)) return true;
if (EXT_FILE_LINE.test(t)) return true;
if (STATUS_LINE.test(t)) return true;
// Short assignee-only lines (e.g. "Miriam Álvarez.") — only if ≤ 40 chars
if (t.length <= 40 && ASSIGNEE_LINE.test(t) && !t.includes('@') && !/[?!]/.test(t)) {
// Avoid stripping real closing lines that are all-caps slogans
if (!/[A-ZÁÉÍÓÚÑ]{4,}/.test(t.replace(/[^A-Za-zÁÉÍÓÚáéíóúÑñ]/g, ''))) {
return true;
}
}
return false;
}
export function captionHasProductionNoise(raw: string | null | undefined): boolean {
if (!raw?.trim()) return false;
return raw.split(/\r?\n/).some((l) => looksLikeProductionNoise(l));
}
/**
* Remove production-noise lines and trailing junk after the real copy.
* Does not invent content — only strips.
*/
export function sanitizePublishCaption(
raw: string | null | undefined,
opts?: { maxLen?: number }
): CaptionSanitizeResult {
const maxLen = opts?.maxLen ?? 2200;
const input = (raw || '').replace(/\r\n/g, '\n').trim();
if (!input) {
return { caption: '', stripped: [], changed: false };
}
const stripped: string[] = [];
const kept: string[] = [];
for (const line of input.split('\n')) {
if (looksLikeProductionNoise(line)) {
stripped.push(line.trim());
continue;
}
kept.push(line);
}
// Collapse trailing empty lines left by stripping
let caption = kept.join('\n').replace(/\n{3,}/g, '\n\n').trim();
if (caption.length > maxLen) caption = caption.slice(0, maxLen).trim();
return {
caption,
stripped,
changed: caption !== input.slice(0, maxLen).trim() || stripped.length > 0,
};
}