Add news research assistant to post editor
This commit is contained in:
@@ -6,7 +6,7 @@ import { runAutomation } from "./automation";
|
||||
export const AI_DAILY_LIMIT_PER_PAGE = 30;
|
||||
|
||||
export async function generateStructured<S extends z.ZodType>(req: {
|
||||
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation";
|
||||
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation" | "research";
|
||||
pageId: string;
|
||||
userId: string;
|
||||
system: string;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
const SEARCH_TIMEOUT_MS = 10_000;
|
||||
const MAX_RESULTS = 8;
|
||||
|
||||
export interface NewsArticle {
|
||||
title: string;
|
||||
url: string;
|
||||
source: string;
|
||||
publishedAt: string | null;
|
||||
description: string;
|
||||
}
|
||||
|
||||
function decodeXml(value: string): string {
|
||||
return value
|
||||
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'|'/g, "'")
|
||||
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Math.min(Number(code), 0x10ffff)));
|
||||
}
|
||||
|
||||
function field(item: string, name: string): string {
|
||||
return decodeXml(item.match(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, "i"))?.[1] ?? "")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */
|
||||
export async function searchNews(query: string): Promise<NewsArticle[]> {
|
||||
const url = new URL("https://www.bing.com/news/search");
|
||||
url.searchParams.set("q", query);
|
||||
url.searchParams.set("format", "rss");
|
||||
url.searchParams.set("setlang", "th-TH");
|
||||
const response = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
|
||||
headers: { accept: "application/rss+xml,application/xml,text/xml", "user-agent": "PagivaContentResearch/1.0" },
|
||||
});
|
||||
if (!response.ok) throw new Error(`news search returned ${response.status}`);
|
||||
const xml = await response.text();
|
||||
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/gi)]
|
||||
.map((match) => {
|
||||
const item = match[1];
|
||||
const rawDate = field(item, "pubDate");
|
||||
const timestamp = Date.parse(rawDate);
|
||||
return {
|
||||
title: field(item, "title"),
|
||||
url: field(item, "link"),
|
||||
source: field(item, "News:Source") || field(item, "source") || "แหล่งข่าว",
|
||||
publishedAt: Number.isNaN(timestamp) ? null : new Date(timestamp).toISOString(),
|
||||
description: field(item, "description").slice(0, 600),
|
||||
} satisfies NewsArticle;
|
||||
})
|
||||
.filter((article) => article.title && /^https?:\/\//.test(article.url))
|
||||
.slice(0, MAX_RESULTS);
|
||||
}
|
||||
@@ -63,6 +63,15 @@ export async function graphPostJson(path: string, accessToken: string, body: Rec
|
||||
return parse(res);
|
||||
}
|
||||
|
||||
/** Uploads binary media to Graph without requiring Meta to fetch a public URL. */
|
||||
export async function graphPostForm(path: string, accessToken: string, body: FormData): Promise<GraphBody> {
|
||||
const res = await fetch(buildUrl(path, accessToken), {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
return parse(res);
|
||||
}
|
||||
|
||||
export async function graphDelete(path: string, accessToken: string): Promise<GraphBody> {
|
||||
const res = await fetch(buildUrl(path, accessToken), { method: "DELETE" });
|
||||
return parse(res);
|
||||
@@ -91,6 +100,7 @@ const GRAPH_ERROR_HINT: Record<number, string> = {
|
||||
32: "เพจนี้เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
|
||||
190: "สิทธิ์เข้าถึงเพจหมดอายุหรือถูกยกเลิก — ไปที่เพจที่เชื่อม แล้วเชื่อมบัญชี Facebook ใหม่",
|
||||
200: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
|
||||
324: "Facebook ไม่พบหรืออ่านไฟล์รูปไม่ได้ — ลองอัปโหลดรูป JPG/PNG ใหม่อีกครั้ง",
|
||||
10: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
|
||||
368: "Facebook บล็อกการกระทำนี้ชั่วคราว (อาจถูกมองว่าเป็นสแปม) ลองใหม่ภายหลัง",
|
||||
506: "โพสต์ซ้ำกับโพสต์ล่าสุด — แก้ข้อความก่อนเผยแพร่",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { bareId, graphDelete, graphGet, graphGetAll, graphPostJson } from "./client";
|
||||
import { bareId, graphDelete, graphGet, graphGetAll, graphPostForm, graphPostJson, UserFacingError } from "./client";
|
||||
import type { PageCredentials } from "./tokens";
|
||||
|
||||
/**
|
||||
@@ -22,6 +22,60 @@ export interface FbPublishResult {
|
||||
permalink: string | null;
|
||||
}
|
||||
|
||||
const MAX_FACEBOOK_IMAGE_BYTES = 8 * 1024 * 1024;
|
||||
const FACEBOOK_IMAGE_TYPES = new Map([
|
||||
["image/jpeg", "image.jpg"],
|
||||
["image/png", "image.png"],
|
||||
]);
|
||||
|
||||
function isAllowedImageUrl(imageUrl: URL): boolean {
|
||||
if (imageUrl.protocol !== "https:" && imageUrl.protocol !== "http:") return false;
|
||||
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (appUrl) {
|
||||
const app = new URL(appUrl);
|
||||
const uploadPrefix = `${app.pathname.replace(/\/$/, "")}/api/uploads/`;
|
||||
if (imageUrl.origin === app.origin && imageUrl.pathname.startsWith(uploadPrefix)) return true;
|
||||
}
|
||||
|
||||
return imageUrl.protocol === "https:" && imageUrl.hostname.endsWith(".public.blob.vercel-storage.com");
|
||||
}
|
||||
|
||||
async function facebookImageSource(imageUrl: string): Promise<{ blob: Blob; filename: string }> {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(imageUrl);
|
||||
} catch {
|
||||
throw new UserFacingError("URL รูปไม่ถูกต้อง กรุณาอัปโหลดรูปใหม่");
|
||||
}
|
||||
if (!isAllowedImageUrl(parsed)) {
|
||||
throw new UserFacingError("URL รูปไม่ได้มาจากพื้นที่จัดเก็บของระบบ กรุณาอัปโหลดรูปใหม่");
|
||||
}
|
||||
|
||||
const response = await fetch(parsed, { cache: "no-store", redirect: "follow" });
|
||||
if (!response.ok) {
|
||||
throw new UserFacingError("ระบบอ่านไฟล์รูปไม่ได้ กรุณาอัปโหลดรูปใหม่");
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() ?? "";
|
||||
const filename = FACEBOOK_IMAGE_TYPES.get(contentType);
|
||||
if (!filename) {
|
||||
throw new UserFacingError("ไฟล์รูปต้องเป็น JPG หรือ PNG กรุณาอัปโหลดรูปใหม่");
|
||||
}
|
||||
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_FACEBOOK_IMAGE_BYTES) {
|
||||
throw new UserFacingError("ไฟล์รูปใหญ่เกิน 8MB กรุณาอัปโหลดรูปที่เล็กลง");
|
||||
}
|
||||
|
||||
const bytes = await response.arrayBuffer();
|
||||
if (bytes.byteLength === 0) throw new UserFacingError("ไฟล์รูปว่างเปล่า กรุณาอัปโหลดรูปใหม่");
|
||||
if (bytes.byteLength > MAX_FACEBOOK_IMAGE_BYTES) {
|
||||
throw new UserFacingError("ไฟล์รูปใหญ่เกิน 8MB กรุณาอัปโหลดรูปที่เล็กลง");
|
||||
}
|
||||
return { blob: new Blob([bytes], { type: contentType }), filename };
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes now or hands Facebook a scheduled_publish_time — Facebook holds
|
||||
* and fires scheduled posts itself, no cron needed.
|
||||
@@ -36,11 +90,12 @@ export async function publishToFacebook(
|
||||
|
||||
let fbPostId: string;
|
||||
if (params.imageUrl) {
|
||||
const res = await graphPostJson(`/${page.fbPageId}/photos`, page.token, {
|
||||
url: params.imageUrl,
|
||||
caption: params.caption,
|
||||
...scheduling,
|
||||
});
|
||||
const image = await facebookImageSource(params.imageUrl);
|
||||
const body = new FormData();
|
||||
body.set("source", image.blob, image.filename);
|
||||
body.set("caption", params.caption);
|
||||
for (const [key, value] of Object.entries(scheduling)) body.set(key, String(value));
|
||||
const res = await graphPostForm(`/${page.fbPageId}/photos`, page.token, body);
|
||||
// Photos return `id` (photo id) and `post_id` (feed post id) — the post id is what the feed edges use.
|
||||
fbPostId = res.post_id ?? res.id;
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user