Diagnose image worker failures and normalize Facebook uploads

This commit is contained in:
Loma Bot Ops
2026-11-23 22:27:53 +07:00
parent 4429e6541b
commit df20406cf5
3 changed files with 36 additions and 3 deletions
+14 -1
View File
@@ -1,5 +1,6 @@
import { bareId, graphDelete, graphGet, graphGetAll, graphPostForm, graphPostJson, UserFacingError } from "./client";
import type { PageCredentials } from "./tokens";
import sharp from "sharp";
/**
* Facebook rejects a scheduled_publish_time under 10 minutes or more than ~30
@@ -73,7 +74,19 @@ async function facebookImageSource(imageUrl: string): Promise<{ blob: Blob; file
if (bytes.byteLength > MAX_FACEBOOK_IMAGE_BYTES) {
throw new UserFacingError("ไฟล์รูปใหญ่เกิน 8MB กรุณาอัปโหลดรูปที่เล็กลง");
}
return { blob: new Blob([bytes], { type: contentType }), filename };
// Re-encode to a baseline JPEG so Graph receives actual image bytes even
// when storage serves a misleading MIME type or the upload has bad metadata.
try {
const metadata = await sharp(Buffer.from(bytes), { limitInputPixels: 40_000_000 }).metadata();
if (!metadata.width || !metadata.height || !["jpeg", "png"].includes(metadata.format ?? "")) throw new Error("Unsupported image");
const normalized = await sharp(Buffer.from(bytes), { limitInputPixels: 40_000_000 })
.rotate().flatten({ background: "#ffffff" }).jpeg({ quality: 88, mozjpeg: true }).toBuffer();
if (normalized.length > MAX_FACEBOOK_IMAGE_BYTES) throw new Error("Image too large after conversion");
return { blob: new Blob([normalized], { type: "image/jpeg" }), filename: "image.jpg" };
} catch (error) {
console.error("[publish:fb] image normalization failed", { message: error instanceof Error ? error.message : String(error), contentType, size: bytes.byteLength });
throw new UserFacingError("ไฟล์รูปเสียหรือแปลงเป็นรูปสำหรับ Facebook ไม่ได้ กรุณาอัปโหลด JPG/PNG ใหม่");
}
}
/**