π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat(facebook): background presets for text-only page posts
Gilad Resisif328583cc3eb
diff --git a/apps/frontend/src/components/new-launch/providers/facebook/facebook.background.ts b/apps/frontend/src/components/new-launch/providers/facebook/facebook.background.tsnew file mode 100644index 000000000..0ed335a9b--- /dev/null+++ b/apps/frontend/src/components/new-launch/providers/facebook/facebook.background.ts@@ -0,0 +1,103 @@+import { FACEBOOK_PRESETS } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';++// Facebook does not expose the real preset assets, so we approximate each+// background's color from its descriptive name (e.g. "Solid purple",+// "Gradient, dark orange-red", "Light blue illustration"). Solids/gradients end+// up close; illustrations collapse to a representative flat tint.++const PALETTE: Record<string, string> = {+ purple: '#8a3ffc',+ magenta: '#d6249f',+ pink: '#ec4899',+ red: '#e0294b',+ orange: '#f97316',+ yellow: '#f4c430',+ green: '#2fbf71',+ teal: '#17a2a2',+ blue: '#2d88ff',+ grey: '#65676b',+ brown: '#8b5e34',+ beige: '#d9c7a7',+ black: '#18191a',+};++// Order colors are searched/emitted in (name order isn't reliable).+const ORDER = Object.keys(PALETTE);++// For names without an explicit color word, key off the subject.+const SUBJECTS: Record<string, string> = {+ heart: 'red',+ flame: 'orange',+ rose: 'pink',+ 'heart-eyes': 'yellow',+ laughter: 'yellow',+ smiling: 'yellow',+ emoji: 'yellow',+ rocket: 'blue',+};++function hexToRgb(hex: string): [number, number, number] {+ const n = parseInt(hex.slice(1), 16);+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];+}++function rgbToHex(r: number, g: number, b: number): string {+ const c = (v: number) =>+ Math.max(0, Math.min(255, Math.round(v)))+ .toString(16)+ .padStart(2, '0');+ return `#${c(r)}${c(g)}${c(b)}`;+}++function mix(hex: string, target: string, amount: number): string {+ const [r, g, b] = hexToRgb(hex);+ const [tr, tg, tb] = hexToRgb(target);+ return rgbToHex(+ r + (tr - r) * amount,+ g + (tg - g) * amount,+ b + (tb - b) * amount+ );+}++function luminance(hex: string): number {+ const [r, g, b] = hexToRgb(hex).map((v) => {+ const s = v / 255;+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);+ });+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;+}++export interface PresetBackground {+ background: string;+ text: string;+}++export function getPresetBackground(+ id: string | undefined+): PresetBackground | undefined {+ if (!id) return undefined;+ const preset = FACEBOOK_PRESETS.find((p) => p.id === id);+ if (!preset) return undefined;++ const name = preset.name.toLowerCase();+ const isLight = /light/.test(name);+ const isDark = /\bdark\b|dark-/.test(name);++ let colors = ORDER.filter((c) => name.includes(c)).map((c) => PALETTE[c]);+ if (!colors.length) {+ const subject = Object.keys(SUBJECTS).find((k) => name.includes(k));+ colors = [PALETTE[subject ? SUBJECTS[subject] : 'grey']];+ }++ colors = colors.map((c) =>+ isLight ? mix(c, '#ffffff', 0.5) : isDark ? mix(c, '#000000', 0.32) : c+ );++ const background =+ name.includes('gradient') && colors.length >= 2+ ? `linear-gradient(135deg, ${colors.join(', ')})`+ : colors[0];++ const text = luminance(colors[0]) > 0.5 ? '#1c1e21' : '#ffffff';+ return { background, text };+}diff --git a/apps/frontend/src/components/new-launch/providers/facebook/facebook.preview.tsx b/apps/frontend/src/components/new-launch/providers/facebook/facebook.preview.tsxindex a782ab54e..bdd8a59a9 100644--- a/apps/frontend/src/components/new-launch/providers/facebook/facebook.preview.tsx+++ b/apps/frontend/src/components/new-launch/providers/facebook/facebook.preview.tsx@@ -3,7 +3,10 @@ import { useLaunchStore } from '@gitroom/frontend/components/new-launch/store';import { useMediaDirectory } from '@gitroom/react/helpers/use.media.directory';import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';import { textSlicer } from '@gitroom/helpers/utils/count.length';+import { FACEBOOK_PRESET_MAX_CHARS } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';+import { getPresetBackground } from '@gitroom/frontend/components/new-launch/providers/facebook/facebook.background';import { FC } from 'react';+import { useFormContext, useWatch } from 'react-hook-form';import { VideoOrImage } from '@gitroom/react/helpers/video.or.image';const Icons = () => {@@ -66,6 +69,25 @@ export const FacebookPreview: FC<{const current = useLaunchStore((state) => state.current);const mediaDir = useMediaDirectory();+ // Facebook only renders the background on text-only posts up to 130 chars, so+ // reflect the real outcome here: the background shows when it will actually be+ // applied, and disappears (plain text) when it would be dropped.+ const control = useFormContext()?.control;+ const preset = useWatch({ control, name: 'text_format_preset_id' }) as+ | string+ | undefined;+ const firstText = stripHtmlValidation(+ 'normal',+ topValue?.[0]?.content || '',+ true+ );+ const background =+ !!preset &&+ !topValue?.[0]?.image?.length &&+ firstText.length <= FACEBOOK_PRESET_MAX_CHARS+ ? getPresetBackground(preset)+ : undefined;+const renderContent = topValue.map((p) => {const newContent = stripHtmlValidation('normal',@@ -129,12 +151,22 @@ export const FacebookPreview: FC<{</div></div></div>- <div- className="text-[14px] font-[400] whitespace-pre-line"- dangerouslySetInnerHTML={{- __html: renderContent?.[0]?.text,- }}- />+ {background ? (+ <div+ className="-mx-[15px] min-h-[320px] flex items-center justify-center text-center px-[32px] py-[32px] text-[28px] font-[700] leading-[36px] whitespace-pre-line break-words"+ style={{ background: background.background, color: background.text }}+ dangerouslySetInnerHTML={{+ __html: renderContent?.[0]?.text,+ }}+ />+ ) : (+ <div+ className="text-[14px] font-[400] whitespace-pre-line"+ dangerouslySetInnerHTML={{+ __html: renderContent?.[0]?.text,+ }}+ />+ )}{!!renderContent?.[0]?.images?.length && (<div className="h-[280px] -mx-[15px] overflow-hidden flex">{renderContent?.[0]?.images.map((image, index) => (diff --git a/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx b/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsxindex acd309256..00b8e1225 100644--- a/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx@@ -4,12 +4,18 @@ import {PostComment,withProvider,} from '@gitroom/frontend/components/new-launch/providers/high.order.provider';-import { FacebookDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';+import {+ FacebookDto,+ FACEBOOK_PRESETS,+} from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';+import { getPresetBackground } from '@gitroom/frontend/components/new-launch/providers/facebook/facebook.background';import { Input } from '@gitroom/react/form/input';import { Select } from '@gitroom/react/form/select';import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';+import { useIntegration } from '@gitroom/frontend/components/launches/helpers/use.integration';import { FacebookPreview } from '@gitroom/frontend/components/new-launch/providers/facebook/facebook.preview';import { useT } from '@gitroom/react/translation/get.transation.service.client';+import { useEffect } from 'react';const postType = [{@@ -24,24 +30,43 @@ const postType = [export const FacebookSettings = () => {const t = useT();- const { register, watch } = useSettings();+ const { register, watch, setValue } = useSettings();+ const { value } = useIntegration();const postCurrentType = watch('post_type');+ const preset = watch('text_format_preset_id');++ // Facebook background presets only render on text-only Page posts (no media).+ const hasMedia = !!value?.some((p) => !!p.image?.length);+ const presetAvailable = postCurrentType !== 'story' && !hasMedia;+ const selectedBg = getPresetBackground(preset);++ // Clear any selected background when it can no longer apply (story / media),+ // so a stray combination never reaches the provider.+ useEffect(() => {+ if (!presetAvailable && preset) {+ setValue('text_format_preset_id', '');+ }+ }, [presetAvailable, preset, setValue]);return (<>- <Select- label="Post Type"- {...register('post_type', {- value: 'post',- })}- >- <option value="">{t('select_post_type', 'Select Post Type...')}</option>- {postType.map((item) => (- <option key={item.value} value={item.value}>- {item.label}+ <div className="pt-[20px]">+ <Select+ label="Post Type"+ {...register('post_type', {+ value: 'post',+ })}+ >+ <option value="">+ {t('select_post_type', 'Select Post Type...')}</option>- ))}- </Select>+ {postType.map((item) => (+ <option key={item.value} value={item.value}>+ {item.label}+ </option>+ ))}+ </Select>+ </div>{postCurrentType !== 'story' && (<Input@@ -49,6 +74,45 @@ export const FacebookSettings = () => {{...register('url')}/>)}++ {presetAvailable && (+ <>+ <Select+ label="Background (applies to text-only posts shorter than 130 characters)"+ hideErrors+ {...register('text_format_preset_id')}+ style={+ selectedBg+ ? { background: selectedBg.background, color: selectedBg.text }+ : undefined+ }+ >+ <option value="" style={{ background: '#ffffff', color: '#1c1e21' }}>+ {t('facebook_background_none', 'None (plain text)')}+ </option>+ {FACEBOOK_PRESETS.map((item) => {+ const bg = getPresetBackground(item.id);+ return (+ <option+ key={item.id}+ value={item.id}+ style={+ bg ? { background: bg.background, color: bg.text } : undefined+ }+ >+ {item.name}+ </option>+ );+ })}+ </Select>+ <div className="text-[12px] opacity-70 mt-[8px]">+ {t(+ 'facebook_background_note',+ 'Unofficial list: the colors shown are approximate, an unsupported background is dropped (published as plain text)'+ )}+ </div>+ </>+ )}</>);};diff --git a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/facebook.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/facebook.dto.tsindex cc6899cb4..f913a95b0 100644--- a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/facebook.dto.ts+++ b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/facebook.dto.ts@@ -1,4 +1,96 @@-import { IsIn, IsOptional, ValidateIf, IsUrl } from 'class-validator';+import { IsIn, IsOptional, IsString, ValidateIf, IsUrl } from 'class-validator';++// Maximum characters Facebook allows on a background ("text format") post.+export const FACEBOOK_PRESET_MAX_CHARS = 130;++export interface FacebookPreset {+ id: string;+ name: string;+}++// Curated catalog of Facebook text-post background presets.+//+// Facebook exposes no documented Graph API edge to enumerate a page's+// `text_format_preset_id` options, so the list has to be hardcoded. These IDs+// appear to be global (same across pages). Source: Publer's documented+// Facebook background list. Background posts are text-only (no media), Pages+// only, and capped at ~130 characters.+export const FACEBOOK_PRESETS: FacebookPreset[] = [+ { id: '106018623298955', name: 'Solid purple' },+ { id: '365653833956649', name: 'Pink tropical plants' },+ { id: '618093735238824', name: 'Brown illustration' },+ { id: '191761991491375', name: '3D hearts' },+ { id: '2193627793985415', name: '3D heart-eyes emojis' },+ { id: '200521337465306', name: '3D flame emojis' },+ { id: '1821844087883360', name: 'Walking yellow illustration' },+ { id: '177465482945164', name: 'Light purple 3D cube pattern' },+ { id: '160419724814650', name: 'Orange with pink illustration' },+ { id: '248623902401250', name: '3D smiling emoji' },+ { id: '240401816771706', name: '3D rose emojis' },+ { id: '1868855943417360', name: '3D crying-laughter emoji' },+ { id: '255989551804163', name: 'Eye pink illustration' },+ { id: '1792915444087912', name: 'Illustration' },+ { id: '1654916007940525', name: 'Light grey illustration' },+ { id: '1679248482160767', name: 'Light blue illustration' },+ { id: '518948401838663', name: 'Pink heart pattern on pink' },+ { id: '423339708139719', name: 'Illustration' },+ { id: '204187940028597', name: 'Solid red' },+ { id: '621731364695726', name: 'Solid red' },+ { id: '518596398537417', name: 'Red illustration' },+ { id: '134273813910336', name: 'Tree red illustration' },+ { id: '217321755510854', name: 'Pink and purple hearts on pink' },+ { id: '323371698179784', name: 'Sunset red illustration' },+ { id: '901751159967576', name: 'Gradient, dark orange-red' },+ { id: '552118025129095', name: 'Brown illustration' },+ { id: '263789377694911', name: 'Apple red illustration' },+ { id: '606643333067842', name: 'Tulip light-orange illustration' },+ { id: '458988134561491', name: 'Cat dark-orange illustration' },+ { id: '548109108916650', name: 'Unicorn red illustration' },+ { id: '175493843120364', name: 'Pink and yellow gradient' },+ { id: '338976169966519', name: 'Stairs beige illustration' },+ { id: '206513879997925', name: 'Spiral beige illustration' },+ { id: '168373304017982', name: 'Cube beige illustration' },+ { id: '1271157196337260', name: 'Solid red' },+ { id: '174496469882866', name: 'Lemon yellow illustration' },+ { id: '862667370603267', name: 'Egg light-yellow illustration' },+ { id: '127541261450947', name: 'Ball green illustration' },+ { id: '218067308976029', name: 'Light grey illustration' },+ { id: '688479024672716', name: 'Gradient, teal light-green' },+ { id: '238863426886624', name: 'Cat light-blue illustration' },+ { id: '301029513638534', name: 'Solid teal' },+ { id: '154977255088164', name: 'Solid teal' },+ { id: '1941912679424590', name: 'Gradient, grey dark-grey' },+ { id: '396343990807392', name: 'Flower teal illustration' },+ { id: '143093446467972', name: 'Blue clouds on dark blue' },+ { id: '161409924510923', name: 'Rocket ship makes heart in sky' },+ { id: '145893972683590', name: 'Solid dark purple' },+ { id: '217761075370932', name: 'Solid blue' },+ { id: '931584293685988', name: 'Wave blue illustration' },+ { id: '148862695775447', name: 'Pink and purple hearts on purple' },+ { id: '100114277230063', name: 'Deep sea blue illustration' },+ { id: '558836317844129', name: 'Spiral purple illustration' },+ { id: '172497526576609', name: 'Watermelon light-purple illustration' },+ { id: '433967226963128', name: 'Solid purple' },+ { id: '197865920864520', name: 'Donut light-purple illustration' },+ { id: '643122496026756', name: 'Pink illustration' },+ { id: '762009070855346', name: 'Balloon light-grey illustration' },+ { id: '228164237768720', name: 'Grey heart pattern on black' },+ { id: '146487026137131', name: 'Rain black illustration' },+ { id: '221828835275596', name: 'Glasses light-grey illustration' },+ { id: '1903718606535395', name: 'Solid red' },+ { id: '1881421442117417', name: 'Solid black' },+ { id: '249307305544279', name: 'Gradient, red-blue' },+ { id: '1777259169190672', name: 'Gradient, purple-magenta' },+ { id: '303063890126415', name: 'Yellow/orange/pink gradient' },+ { id: '122708641613922', name: 'Gradient, dark-grey-black' },+ { id: '319468561816672', name: 'Dark blue illustration' },+ { id: '121945541697934', name: 'Pink illustration' },+ { id: '288211338285858', name: 'Blue illustration' },+ { id: '446330032368780', name: 'Gradient, red' },+ { id: '219266485227663', name: 'Solid magenta' },+ { id: '1289741387813798', name: 'Solid dark red' },+ { id: '1365883126823705', name: 'Solid blue' },+];export class FacebookDto {@IsOptional()@@ -9,4 +101,11 @@ export class FacebookDto {@IsIn(['post', 'story'])@IsOptional()post_type?: 'post' | 'story';++ // Optional Facebook background preset for text-only posts. Kept permissive+ // (@IsString rather than @IsIn) so existing posts without the field still+ // validate and future preset drift on Facebook's side doesn't hard-fail.+ @IsOptional()+ @IsString()+ text_format_preset_id?: string;}diff --git a/libraries/nestjs-libraries/src/integrations/social.abstract.ts b/libraries/nestjs-libraries/src/integrations/social.abstract.tsindex cc33ead76..02d9bfb2f 100644--- a/libraries/nestjs-libraries/src/integrations/social.abstract.ts+++ b/libraries/nestjs-libraries/src/integrations/social.abstract.ts@@ -207,10 +207,6 @@ export abstract class SocialAbstract {return request;}- if (totalRetries > 2) {- throw new BadBody(identifier, '{}', options.body || '{}', message);- }-let json = '{}';try {json = await request.text();@@ -218,6 +214,12 @@ export abstract class SocialAbstract {json = '{}';}+ if (totalRetries > 2) {+ // Include the platform's actual response body so the failure is+ // diagnosable, instead of an empty '{}'.+ throw new BadBody(identifier, json, options.body || '{}', message);+ }+const handleError = this.handleErrors(json || '{}', request.status);if (diff --git a/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts b/libraries/nestjs-libraries/src/integrations/social/facebook.provider.tsindex f885c1360..7c287152b 100644--- a/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts@@ -11,7 +11,10 @@ import {SocialAbstract,ValidityMedia,} from '@gitroom/nestjs-libraries/integrations/social.abstract';-import { FacebookDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';+import {+ FacebookDto,+ FACEBOOK_PRESET_MAX_CHARS,+} from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';import { DribbbleDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/dribbble.dto';import { Integration } from '@prisma/client';import { hasExtension } from '@gitroom/helpers/utils/has.extension';@@ -613,30 +616,90 @@ export class FacebookProvider extends SocialAbstract implements SocialProvider {}));- const {- id: postId,- permalink_url,- ...all- } = await (- await this.fetch(- `https://graph.facebook.com/v20.0/${id}/feed?access_token=${accessToken}&fields=id,permalink_url`,- {- method: 'POST',- headers: {- 'Content-Type': 'application/json',+ // Background presets are only valid on text-only posts (no media) and+ // Facebook caps them at ~130 chars, so we only attach the preset when it+ // can apply.+ const presetId =+ !uploadPhotos?.length &&+ firstPost?.settings?.text_format_preset_id &&+ (firstPost.message?.length || 0) <= FACEBOOK_PRESET_MAX_CHARS+ ? firstPost.settings.text_format_preset_id+ : undefined;++ const publishFeed = async (withPreset: boolean) =>+ (+ await this.fetch(+ `https://graph.facebook.com/v20.0/${id}/feed?access_token=${accessToken}&fields=id,permalink_url`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ ...(uploadPhotos?.length+ ? { attached_media: uploadPhotos }+ : {}),+ ...(firstPost?.settings?.url+ ? { link: firstPost.settings.url }+ : {}),+ ...(withPreset && presetId+ ? { text_format_preset_id: presetId }+ : {}),+ message: firstPost.message,+ published: true,+ }),},- body: JSON.stringify({- ...(uploadPhotos?.length ? { attached_media: uploadPhotos } : {}),- ...(firstPost?.settings?.url- ? { link: firstPost.settings.url }- : {}),- message: firstPost.message,- published: true,- }),- },- 'finalize upload'- )- ).json();+ 'finalize upload'+ )+ ).json();++ // Facebook exposes no official preset list and adds/retires backgrounds+ // over time, so a stale text_format_preset_id can make FB reject the whole+ // post. Observed Graph API responses for a bad preset:+ // - malformed id -> HTTP 400, code 100, message names+ // "text_format_preset_id" explicitly+ // - retired numeric id -> HTTP 500, code 1, generic "unknown error"+ // (our fetch() retries 500s and then reports it with the body stripped)+ // So retry once without the preset on an explicit preset error or a+ // generic/unknown failure, but never on a recognized auth/token error+ // (dropping the background can't fix that). A retry that only succeeds once+ // the preset is removed confirms the preset was the cause.+ const isPresetRejection = (err: any): boolean => {+ const detail = `${err?.details?.[0]?.json ?? ''} ${err?.message ?? ''}`;+ if (+ /access token|re-authenticate|revoked|"code":\s*190\b/i.test(detail)+ ) {+ return false;+ }+ return (+ /text_format_preset_id/i.test(detail) ||+ /"code":\s*1\b/.test(detail) ||+ String(err?.message) === 'Unknown Error'+ );+ };++ let feedResult: any;+ try {+ feedResult = await publishFeed(!!presetId);+ } catch (err) {+ if (!presetId || !isPresetRejection(err)) {+ throw err;+ }+ // Surface the (recovered) rejection in the logs, since the fallback+ // below makes the activity succeed and Facebook's error would otherwise+ // be swallowed silently.+ console.warn(+ 'Facebook rejected text_format_preset_id β dropping the background and publishing as plain text',+ {+ preset: presetId,+ facebook: (err as any)?.details?.[0]?.json,+ message: (err as any)?.message,+ }+ );+ feedResult = await publishFeed(false);+ }++ const { id: postId, permalink_url, ...all } = feedResult;finalUrl = permalink_url;finalId = postId;