Initial commit: page-manager Next.js app with Coolify deploy support

Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents
for deployment to Coolify: in-container cron scheduler
(scripts/cron-runner.mjs) and disk-based upload storage served via
/api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health
for container health checks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
chaloemphong
2026-11-22 11:52:17 +07:00
commit 9d32552457
155 changed files with 22174 additions and 0 deletions
+130
View File
@@ -0,0 +1,130 @@
// Thin Graph API wrapper. Every call takes an explicit access token: page-level
// endpoints need that page's token (lib/facebook/tokens.ts); /me/accounts uses a
// token source (Facebook login or system user); /debug_token uses the app token.
// Single place to bump the Graph version. Check Meta's changelog for the
// currently supported versions before raising it.
export const GRAPH_API_VERSION = "v21.0";
const GRAPH_BASE = `https://graph.facebook.com/${GRAPH_API_VERSION}`;
export class FacebookApiError extends Error {
constructor(
message: string,
public readonly code?: number,
public readonly subcode?: number,
public readonly type?: string,
public readonly raw?: unknown
) {
super(message);
this.name = "FacebookApiError";
}
}
type Params = Record<string, string | number | boolean | undefined>;
function buildUrl(path: string, accessToken: string, params: Params = {}): string {
const url = new URL(`${GRAPH_BASE}${path}`);
url.searchParams.set("access_token", accessToken);
for (const [k, v] of Object.entries(params)) {
if (v !== undefined) url.searchParams.set(k, String(v));
}
return url.toString();
}
async function parse(res: Response) {
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error) {
const err = body.error ?? {};
throw new FacebookApiError(
err.message ?? `Graph API request failed (${res.status})`,
err.code,
err.error_subcode,
err.type,
body
);
}
return body;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type GraphBody = any;
export async function graphGet(path: string, accessToken: string, params: Params = {}): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken, params), { cache: "no-store" });
return parse(res);
}
export async function graphPostJson(path: string, accessToken: string, body: Record<string, unknown>): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(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);
}
/**
* Follows `paging.next` until exhausted (or maxPages). `paging.next` is an
* absolute URL that already carries token + cursor, so it is fetched as-is.
*/
export async function graphGetAll<T>(path: string, accessToken: string, params: Params = {}, maxPages = 20): Promise<T[]> {
const items: T[] = [];
let body = await graphGet(path, accessToken, params);
for (let page = 0; page < maxPages; page++) {
items.push(...((body.data ?? []) as T[]));
const next: string | undefined = body.paging?.next;
if (!next) break;
body = await parse(await fetch(next, { cache: "no-store" }));
}
return items;
}
/** Common Graph error codes → what the user should do next. */
const GRAPH_ERROR_HINT: Record<number, string> = {
4: "เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
17: "เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
32: "เพจนี้เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
190: "สิทธิ์เข้าถึงเพจหมดอายุหรือถูกยกเลิก — ไปที่เพจที่เชื่อม แล้วเชื่อมบัญชี Facebook ใหม่",
200: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
10: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
368: "Facebook บล็อกการกระทำนี้ชั่วคราว (อาจถูกมองว่าเป็นสแปม) ลองใหม่ภายหลัง",
506: "โพสต์ซ้ำกับโพสต์ล่าสุด — แก้ข้อความก่อนเผยแพร่",
1366046: "รูปไม่ผ่านเงื่อนไขของ Facebook — ลองรูป JPG/PNG ขนาดเล็กลง",
};
/**
* Logs the full Graph error server-side and returns a safe Thai message for
* the client — raw responses can carry account/asset ids.
*/
export function safeFacebookErrorMessage(e: unknown, context: string): string {
if (e instanceof FacebookApiError) {
console.error(`[${context}] Graph API error`, { message: e.message, code: e.code, subcode: e.subcode, type: e.type, raw: e.raw });
const hint = e.code !== undefined ? GRAPH_ERROR_HINT[e.code] : undefined;
if (hint) return `${hint} (code ${e.code})`;
return e.code
? `เชื่อมต่อ Facebook ไม่สำเร็จ (code ${e.code}) ลองใหม่หรือติดต่อผู้ดูแล`
: "เชื่อมต่อ Facebook ไม่สำเร็จ ลองใหม่หรือติดต่อผู้ดูแล";
}
if (e instanceof UserFacingError) return e.message;
console.error(`[${context}] Unexpected error`, e);
return "เกิดข้อผิดพลาดที่ไม่คาดคิด ลองใหม่หรือติดต่อผู้ดูแล";
}
/** An error whose message is already safe Thai text for the UI. */
export class UserFacingError extends Error {
constructor(message: string) {
super(message);
this.name = "UserFacingError";
}
}
/** Graph ids come back bare ("123") or page-prefixed ("pageId_123"); compare on the suffix. */
export function bareId(id: string): string {
const parts = id.split("_");
return parts[parts.length - 1];
}
+160
View File
@@ -0,0 +1,160 @@
import { graphGet, graphPostJson } from "./client";
import type { PageCredentials } from "./tokens";
/**
* Page inbox (Messenger + Instagram DM), read live from Graph. Message text
* is never written to the database — conversations are other people's private
* messages; the DB keeps only Conversation metadata for the bot.
*/
export type InboxPlatform = "messenger" | "instagram";
export interface Participant {
id: string;
name: string;
}
export interface InboxConversation {
id: string;
snippet: string;
updatedTime: string;
unreadCount: number;
contacts: Participant[];
}
export interface InboxMessage {
id: string;
createdTime: string;
fromId: string;
fromName: string;
fromPage: boolean;
text: string;
imageUrls: string[];
}
interface RawParticipant {
id: string;
name?: string;
username?: string;
}
function contactsOf(raw: RawParticipant[] | undefined, page: PageCredentials): Participant[] {
return (raw ?? [])
.filter((p) => p.id !== page.fbPageId && p.id !== page.igUserId)
.map((p) => ({ id: p.id, name: p.name || p.username || "ไม่ทราบชื่อ" }));
}
export async function listConversations(
page: PageCredentials,
platform: InboxPlatform,
{ limit = 25, after }: { limit?: number; after?: string } = {}
): Promise<{ conversations: InboxConversation[]; nextCursor: string | null }> {
const res = await graphGet(`/${page.fbPageId}/conversations`, page.token, {
platform,
limit,
after,
fields: "id,snippet,updated_time,unread_count,participants",
});
const conversations: InboxConversation[] = (res.data ?? []).map(
(c: { id: string; snippet?: string; updated_time: string; unread_count?: number; participants?: { data?: RawParticipant[] } }) => ({
id: c.id,
snippet: c.snippet ?? "",
updatedTime: c.updated_time,
unreadCount: c.unread_count ?? 0,
contacts: contactsOf(c.participants?.data, page),
})
);
return { conversations, nextCursor: res.paging?.cursors?.after ?? null };
}
/** Oldest first, like every chat UI. */
export async function listMessages(page: PageCredentials, conversationId: string, limit = 40): Promise<InboxMessage[]> {
const res = await graphGet(`/${conversationId}/messages`, page.token, {
limit,
fields: "id,created_time,from,message,attachments{image_data}",
});
return (res.data ?? [])
.map(
(m: {
id: string;
created_time: string;
from?: RawParticipant;
message?: string;
attachments?: { data?: Array<{ image_data?: { url?: string; preview_url?: string } }> };
}) => ({
id: m.id,
createdTime: m.created_time,
fromId: m.from?.id ?? "",
fromName: m.from?.name || m.from?.username || "ไม่ทราบชื่อ",
fromPage: m.from?.id === page.fbPageId || m.from?.id === page.igUserId,
text: m.message ?? "",
imageUrls: (m.attachments?.data ?? [])
.map((a) => a.image_data?.preview_url ?? a.image_data?.url)
.filter((u): u is string => Boolean(u)),
})
)
.reverse();
}
/**
* The person on the other end, resolved from Graph — never trust a PSID from
* the client, or the page could be used to message someone who never wrote in.
*/
export async function resolveRecipient(page: PageCredentials, conversationId: string): Promise<Participant | null> {
const res = await graphGet(`/${conversationId}`, page.token, { fields: "participants" });
return contactsOf(res.participants?.data, page)[0] ?? null;
}
export function lastInboundAt(messages: InboxMessage[]): string | null {
const inbound = messages.filter((m) => !m.fromPage);
return inbound.length ? inbound[inbound.length - 1].createdTime : null;
}
/** RESPONSE = reply inside the 24h window. No message tags: misuse risks the page's messaging permission. */
export async function sendTextMessage(page: PageCredentials, recipientId: string, text: string): Promise<string> {
const res = await graphPostJson(`/${page.fbPageId}/messages`, page.token, {
recipient: { id: recipientId },
message: { text },
messaging_type: "RESPONSE",
});
return res.message_id ?? "";
}
export async function sendImageMessage(page: PageCredentials, recipientId: string, imageUrl: string): Promise<string> {
const res = await graphPostJson(`/${page.fbPageId}/messages`, page.token, {
recipient: { id: recipientId },
message: { attachment: { type: "image", payload: { url: imageUrl, is_reusable: true } } },
messaging_type: "RESPONSE",
});
return res.message_id ?? "";
}
export async function sendSenderAction(
page: PageCredentials,
recipientId: string,
action: "mark_seen" | "typing_on" | "typing_off"
): Promise<void> {
await graphPostJson(`/${page.fbPageId}/messages`, page.token, { recipient: { id: recipientId }, sender_action: action });
}
/**
* Messenger private reply to a comment. Only works for comments on the page's
* own posts, once per comment, within 7 days. Comments in Groups fail with
* (#100) subcode 33 every time.
*/
export async function sendPrivateReply(page: PageCredentials, commentId: string, text: string): Promise<string> {
const res = await graphPostJson(`/${commentId}/private_replies`, page.token, { message: text });
return res.id ?? res.message_id ?? "";
}
/** Public reply under the comment (FB: /comments, IG: /replies). */
export async function replyToComment(
page: PageCredentials,
commentId: string,
text: string,
platform: "facebook" | "instagram"
): Promise<string> {
const edge = platform === "instagram" ? "replies" : "comments";
const res = await graphPostJson(`/${commentId}/${edge}`, page.token, { message: text });
return res.id ?? "";
}
+54
View File
@@ -0,0 +1,54 @@
import { graphGet } from "./client";
import type { PageCredentials } from "./tokens";
interface InsightMetric {
name: string;
values: Array<{ value: number | Record<string, number>; end_time?: string }>;
}
function latest(metrics: InsightMetric[], name: string): number {
const m = metrics.find((x) => x.name === name);
const v = m?.values?.[m.values.length - 1]?.value;
return typeof v === "number" ? v : 0;
}
/**
* page_impressions / page_engaged_users / page_fans / page_fan_adds are
* deprecated ("(#100) The value must be a valid insights metric"). These are
* the closest supported ones; the daily follower delta is derived by the cron
* from yesterday's snapshot since page_fan_adds has no replacement.
*/
export async function getPageDailyInsights(page: PageCredentials) {
const res = await graphGet(`/${page.fbPageId}/insights`, page.token, {
metric: "page_views_total,page_post_engagements,page_follows",
period: "day",
});
const data: InsightMetric[] = res.data ?? [];
return {
views: latest(data, "page_views_total"),
engagements: latest(data, "page_post_engagements"),
follows: latest(data, "page_follows"),
raw: res,
};
}
/**
* Metric names here are unverified against the current Graph version — if
* Meta rejects one, swap it and keep `raw` so history can be re-derived.
*/
export async function getPostInsights(page: PageCredentials, fbPostId: string) {
const id = fbPostId.includes("_") ? fbPostId : `${page.fbPageId}_${fbPostId}`;
const res = await graphGet(`/${id}/insights`, page.token, {
metric: "post_impressions,post_engaged_users,post_reactions_by_type_total",
});
const data: InsightMetric[] = res.data ?? [];
const reactionsRaw = data.find((d) => d.name === "post_reactions_by_type_total")?.values?.[0]?.value;
const reactions =
reactionsRaw && typeof reactionsRaw === "object" ? Object.values(reactionsRaw).reduce((a, b) => a + b, 0) : 0;
return {
impressions: latest(data, "post_impressions"),
engaged: latest(data, "post_engaged_users"),
reactions,
raw: res,
};
}
+21
View File
@@ -0,0 +1,21 @@
// Pure policy constants shared by API routes and the browser composer.
// Kept free of Graph/env imports so the client bundle never pulls server code.
/** Meta rejects longer text on the send API. */
export const MAX_MESSAGE_LENGTH = 2000;
/**
* A page may reply freely for 24h after the person's last message; after that
* the send API needs a message tag, so the UI blocks the send instead.
*/
export const MESSAGING_WINDOW_MS = 24 * 60 * 60 * 1000;
export function isWithinMessagingWindow(lastInboundIso: string | null): boolean {
if (!lastInboundIso) return false;
return Date.now() - new Date(lastInboundIso).getTime() < MESSAGING_WINDOW_MS;
}
export function windowRemainingMs(lastInboundIso: string | null): number {
if (!lastInboundIso) return 0;
return Math.max(0, MESSAGING_WINDOW_MS - (Date.now() - new Date(lastInboundIso).getTime()));
}
+125
View File
@@ -0,0 +1,125 @@
import { SignJWT, jwtVerify } from "jose";
import { GRAPH_API_VERSION, graphGet, UserFacingError } from "./client";
// "Login with Facebook" for connecting pages. The person granting access must
// be an admin of the pages; while the Meta app is in Development mode they
// must also have a role on the app (admin/developer/tester).
export const OAUTH_STATE_COOKIE = "pm_fb_oauth";
const STATE_TTL_SECONDS = 10 * 60;
/** Overridable with META_OAUTH_SCOPES (comma separated) when the app lacks a product, e.g. Instagram. */
export const DEFAULT_SCOPES = [
"pages_show_list",
"pages_read_engagement",
"pages_manage_metadata",
"pages_manage_posts",
"pages_read_user_content",
"pages_manage_engagement",
"pages_messaging",
"read_insights",
"business_management",
"instagram_basic",
"instagram_content_publish",
"instagram_manage_comments",
"instagram_manage_messages",
];
function appCredentials() {
const id = process.env.META_APP_ID;
const secret = process.env.META_APP_SECRET;
if (!id || !secret) throw new UserFacingError("ยังไม่ได้ตั้ง META_APP_ID / META_APP_SECRET");
return { id, secret };
}
/** App access token — used as the inspector for /debug_token. */
export function appAccessToken(): string | null {
const id = process.env.META_APP_ID;
const secret = process.env.META_APP_SECRET;
return id && secret ? `${id}|${secret}` : null;
}
export function oauthRedirectUri(origin: string): string {
return `${process.env.NEXT_PUBLIC_APP_URL || origin}/api/facebook/oauth/callback`;
}
export function oauthScopes(): string[] {
const raw = process.env.META_OAUTH_SCOPES;
return raw ? raw.split(",").map((s) => s.trim()).filter(Boolean) : DEFAULT_SCOPES;
}
function stateSecret() {
const s = process.env.SESSION_SECRET;
if (!s) throw new Error("SESSION_SECRET env var is not set");
return new TextEncoder().encode(s);
}
/**
* Signed state bound to the user who started the flow. The callback can't
* rely on the session cookie (SameSite=Strict is not sent on the cross-site
* redirect back from facebook.com), so this Lax cookie carries the identity.
*/
export async function createOAuthState(userId: string): Promise<{ nonce: string; cookie: string }> {
const nonce = crypto.randomUUID();
const cookie = await new SignJWT({ nonce })
.setProtectedHeader({ alg: "HS256" })
.setSubject(userId)
.setIssuedAt()
.setExpirationTime(`${STATE_TTL_SECONDS}s`)
.sign(stateSecret());
return { nonce, cookie };
}
export async function verifyOAuthState(cookie: string | undefined, nonce: string | null): Promise<string | null> {
if (!cookie || !nonce) return null;
try {
const { payload } = await jwtVerify(cookie, stateSecret());
return payload.nonce === nonce && payload.sub ? payload.sub : null;
} catch {
return null;
}
}
export function authorizeUrl(origin: string, nonce: string): string {
const { id } = appCredentials();
const url = new URL(`https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth`);
url.searchParams.set("client_id", id);
url.searchParams.set("redirect_uri", oauthRedirectUri(origin));
url.searchParams.set("state", nonce);
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", oauthScopes().join(","));
// Re-show declined permissions instead of silently keeping the old grant.
url.searchParams.set("auth_type", "rerequest");
return url.toString();
}
async function tokenRequest(params: Record<string, string>) {
const url = new URL(`https://graph.facebook.com/${GRAPH_API_VERSION}/oauth/access_token`);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const res = await fetch(url, { cache: "no-store" });
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error || !body.access_token) {
console.error("[fb:oauth] token exchange failed", body.error ?? res.status);
throw new UserFacingError("แลก token กับ Facebook ไม่สำเร็จ ลองเชื่อมใหม่อีกครั้ง");
}
return body as { access_token: string; expires_in?: number };
}
/** code → short-lived user token → long-lived user token (~60 days). */
export async function exchangeCode(origin: string, code: string) {
const { id, secret } = appCredentials();
const short = await tokenRequest({ client_id: id, client_secret: secret, redirect_uri: oauthRedirectUri(origin), code });
const long = await tokenRequest({ grant_type: "fb_exchange_token", client_id: id, client_secret: secret, fb_exchange_token: short.access_token });
const me = await graphGet("/me", long.access_token, { fields: "id,name" });
const perms = await graphGet("/me/permissions", long.access_token);
const scopes: string[] = (perms.data ?? [])
.filter((p: { status: string }) => p.status === "granted")
.map((p: { permission: string }) => p.permission);
return {
token: long.access_token,
expiresAt: long.expires_in ? new Date(Date.now() + long.expires_in * 1000) : null,
fbUserId: me.id as string,
name: me.name as string,
scopes,
};
}
+148
View File
@@ -0,0 +1,148 @@
import { graphGet, graphGetAll, graphPostJson, graphDelete, FacebookApiError } from "./client";
import { appAccessToken } from "./oauth";
export interface AvailablePage {
fbPageId: string;
name: string;
pictureUrl: string | null;
accessToken: string;
igUserId: string | null;
igUsername: string | null;
tasks: string[];
connectionId: string | null;
}
interface RawAccount {
id: string;
name: string;
access_token?: string;
tasks?: string[];
picture?: { data?: { url?: string } };
instagram_business_account?: { id: string; username?: string };
}
/** Pages a single user/system-user token can manage, each with its own page token. */
export async function listPagesForToken(token: string): Promise<AvailablePage[]> {
const rows = await graphGetAll<RawAccount>("/me/accounts", token, {
fields: "id,name,access_token,tasks,picture{url},instagram_business_account{id,username}",
limit: 100,
});
return rows
.filter((r) => r.access_token)
.map((r) => ({
fbPageId: r.id,
name: r.name,
pictureUrl: r.picture?.data?.url ?? null,
accessToken: r.access_token!,
igUserId: r.instagram_business_account?.id ?? null,
igUsername: r.instagram_business_account?.username ?? null,
tasks: r.tasks ?? [],
connectionId: null,
}));
}
export interface PageSource {
/** MetaConnection.id, or null for the system user token */
connectionId: string | null;
label: string;
token: string;
}
/**
* Every page reachable from any token source: the optional system user token
* (env) and each "Login with Facebook" connection. Page tokens minted from a
* system user or a long-lived user token do not expire, but die when the
* person loses page access or permissions change — token-health catches that.
* A failing source is reported, not fatal.
*/
export async function listAvailablePages(sources: PageSource[]): Promise<{ pages: AvailablePage[]; errors: string[] }> {
const seen = new Map<string, AvailablePage>();
const errors: string[] = [];
for (const s of sources) {
try {
for (const p of await listPagesForToken(s.token)) {
if (!seen.has(p.fbPageId)) seen.set(p.fbPageId, { ...p, connectionId: s.connectionId });
}
} catch (e) {
console.error(`[pages:available] source ${s.label} failed`, e);
errors.push(`${s.label}: ${e instanceof FacebookApiError ? `${e.message} (code ${e.code})` : (e as Error).message}`);
}
}
return { pages: [...seen.values()], errors };
}
export function systemUserSource(): PageSource | null {
const token = process.env.META_SYSTEM_USER_TOKEN;
return token ? { connectionId: null, label: "System user", token } : null;
}
export const WEBHOOK_FIELDS = ["messages", "messaging_postbacks", "feed"] as const;
/** Subscribes our app to this page's webhook events. */
export async function subscribePageWebhook(fbPageId: string, pageToken: string): Promise<void> {
await graphPostJson(`/${fbPageId}/subscribed_apps`, pageToken, {
subscribed_fields: WEBHOOK_FIELDS.join(","),
});
}
export async function unsubscribePageWebhook(fbPageId: string, pageToken: string): Promise<void> {
await graphDelete(`/${fbPageId}/subscribed_apps`, pageToken);
}
export interface TokenHealth {
valid: boolean;
scopes: string[];
missingScopes: string[];
detail: string | null;
}
export const REQUIRED_SCOPES = [
"pages_show_list",
"pages_read_engagement",
"pages_manage_metadata",
"pages_manage_posts",
"pages_read_user_content",
"pages_manage_engagement",
"pages_messaging",
"read_insights",
] as const;
export const INSTAGRAM_SCOPES = [
"instagram_basic",
"instagram_content_publish",
"instagram_manage_comments",
"instagram_manage_messages",
] as const;
/** debug_token on a page token. Inspector = app access token (falls back to the token itself). */
export async function checkTokenHealth(pageToken: string, needsInstagram: boolean): Promise<TokenHealth> {
try {
const res = await graphGet("/debug_token", appAccessToken() ?? pageToken, { input_token: pageToken });
const data = res.data ?? {};
const scopes: string[] = data.scopes ?? [];
const required: readonly string[] = needsInstagram ? [...REQUIRED_SCOPES, ...INSTAGRAM_SCOPES] : REQUIRED_SCOPES;
const missingScopes = required.filter((s) => !scopes.includes(s));
const valid = data.is_valid === true;
return {
valid,
scopes,
missingScopes,
detail: valid ? null : data.error?.message ?? "token ใช้งานไม่ได้",
};
} catch (e) {
return {
valid: false,
scopes: [],
missingScopes: [],
detail: e instanceof FacebookApiError ? `${e.message} (code ${e.code})` : (e as Error).message,
};
}
}
export async function listSubscribedFields(fbPageId: string, pageToken: string): Promise<string[]> {
const res = await graphGet(`/${fbPageId}/subscribed_apps`, pageToken);
const appId = process.env.META_APP_ID;
const apps: Array<{ id: string; subscribed_fields?: string[] }> = res.data ?? [];
const ours = appId ? apps.find((a) => a.id === appId) : apps[0];
return ours?.subscribed_fields ?? [];
}
+80
View File
@@ -0,0 +1,80 @@
import { bareId, graphDelete, graphGet, graphGetAll, graphPostJson } from "./client";
import type { PageCredentials } from "./tokens";
/**
* Facebook rejects a scheduled_publish_time under 10 minutes or more than ~30
* days out with a bare "(#100) The specified scheduled publish time was
* invalid." 28 days is what pages accept in practice.
*/
export const MIN_SCHEDULE_MINUTES = 10;
export const MAX_SCHEDULE_DAYS = 28;
export function scheduleTimeProblem(when: Date, now: Date = new Date()): string | null {
const minutesOut = (when.getTime() - now.getTime()) / 60000;
if (Number.isNaN(minutesOut)) return "เวลาที่ตั้งไม่ถูกต้อง";
if (minutesOut < MIN_SCHEDULE_MINUTES) return `ต้องตั้งเวลาล่วงหน้าอย่างน้อย ${MIN_SCHEDULE_MINUTES} นาที`;
if (minutesOut > MAX_SCHEDULE_DAYS * 24 * 60) return `ตั้งเวลาล่วงหน้าได้ไม่เกิน ${MAX_SCHEDULE_DAYS} วัน`;
return null;
}
export interface FbPublishResult {
fbPostId: string;
permalink: string | null;
}
/**
* Publishes now or hands Facebook a scheduled_publish_time — Facebook holds
* and fires scheduled posts itself, no cron needed.
*/
export async function publishToFacebook(
page: PageCredentials,
params: { caption: string; imageUrl: string | null; scheduledAt: Date | null }
): Promise<FbPublishResult> {
const scheduling = params.scheduledAt
? { published: false, scheduled_publish_time: Math.floor(params.scheduledAt.getTime() / 1000) }
: { published: true };
let fbPostId: string;
if (params.imageUrl) {
const res = await graphPostJson(`/${page.fbPageId}/photos`, page.token, {
url: params.imageUrl,
caption: params.caption,
...scheduling,
});
// 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 {
const res = await graphPostJson(`/${page.fbPageId}/feed`, page.token, {
message: params.caption,
...scheduling,
});
fbPostId = res.id;
}
let permalink: string | null = null;
if (!params.scheduledAt) {
permalink = await fetchPermalink(page, fbPostId).catch(() => null);
}
return { fbPostId, permalink };
}
export async function fetchPermalink(page: PageCredentials, fbPostId: string): Promise<string | null> {
const id = fbPostId.includes("_") ? fbPostId : `${page.fbPageId}_${fbPostId}`;
const res = await graphGet(`/${id}`, page.token, { fields: "permalink_url" });
return res.permalink_url ?? null;
}
export async function cancelScheduledFacebookPost(page: PageCredentials, fbPostId: string): Promise<void> {
await graphDelete(`/${fbPostId}`, page.token);
}
/** What the page itself reports as published vs still queued, as bare ids. */
export async function getPageQueueState(page: PageCredentials): Promise<{ published: Set<string>; scheduled: Set<string> }> {
const [published, scheduled] = await Promise.all(
(["published_posts", "scheduled_posts"] as const).map(async (edge) => {
const rows = await graphGetAll<{ id: string }>(`/${page.fbPageId}/${edge}`, page.token, { fields: "id", limit: 100 }, 10);
return new Set(rows.map((r) => bareId(r.id)));
})
);
return { published, scheduled };
}
+61
View File
@@ -0,0 +1,61 @@
import { prisma } from "@/lib/db";
import { decryptToken } from "@/lib/crypto/tokenBox";
import { UserFacingError } from "./client";
import { systemUserSource, type PageSource } from "./pages";
// The only module that reads Page.tokenCipher. Decrypted tokens stay in
// process memory for a short TTL so a revoked/rotated token is not held long.
const TTL_MS = 30 * 60 * 1000;
const globalForTokens = globalThis as unknown as {
pageTokens?: Map<string, { token: string; fbPageId: string; at: number }>;
};
const cache = (globalForTokens.pageTokens ??= new Map());
export interface PageCredentials {
/** Page.id in our DB */
id: string;
fbPageId: string;
igUserId: string | null;
token: string;
}
/** Resolves credentials by our Page.id. Throws a user-facing error if the page is not usable. */
export async function getPageCredentials(pageId: string): Promise<PageCredentials> {
const page = await prisma.page.findUnique({
where: { id: pageId },
select: { id: true, fbPageId: true, igUserId: true, tokenCipher: true, status: true },
});
if (!page) throw new UserFacingError("ไม่พบเพจนี้ในระบบ");
if (page.status === "DISCONNECTED") throw new UserFacingError("เพจนี้ถูกถอดการเชื่อมต่อแล้ว");
const hit = cache.get(page.id);
if (hit && Date.now() - hit.at < TTL_MS) {
return { id: page.id, fbPageId: page.fbPageId, igUserId: page.igUserId, token: hit.token };
}
const token = decryptToken(page.tokenCipher);
cache.set(page.id, { token, fbPageId: page.fbPageId, at: Date.now() });
return { id: page.id, fbPageId: page.fbPageId, igUserId: page.igUserId, token };
}
/** Webhooks identify pages by their Facebook id. Returns null for pages we don't manage. */
export async function getPageCredentialsByFbId(fbPageId: string): Promise<PageCredentials | null> {
const page = await prisma.page.findUnique({ where: { fbPageId }, select: { id: true, status: true } });
if (!page || page.status === "DISCONNECTED") return null;
return getPageCredentials(page.id);
}
export function forgetPageToken(pageId: string) {
cache.delete(pageId);
}
/** Every token source for listing pages: system user (env, optional) + each Facebook login connection. */
export async function getPageSources(): Promise<PageSource[]> {
const sources: PageSource[] = [];
const sys = systemUserSource();
if (sys) sources.push(sys);
const connections = await prisma.metaConnection.findMany({ orderBy: { createdAt: "asc" } });
for (const c of connections) {
sources.push({ connectionId: c.id, label: c.name, token: decryptToken(c.tokenCipher) });
}
return sources;
}