Skip to content

Conversation

jbenton
Copy link

@jbenton jbenton commented Jun 20, 2025

Uses OpenGraph scraping for LinkedIn, API link parameter for Facebook, and app.bsky.embed.external for Bluesky. Adds PostizBot user agents to metadata fetching to make it distinguishable to firewalls.

What kind of change does this PR introduce?

Before, Postiz posts to Bluesky, LinkedIn, and Facebook would appear without dedicated link previews. They'd appear as plain URLs, without the headline/description/thumbnail you'd get if you posted to the platforms directly. This PR adds custom code for those three platforms to deliver those URLs as distinct objects in the ways their various APIs prefer. Now there are link previews!

Why was this change needed?

I was frustrated seeing these subpar posts appear on social networks important to my website, and it was preventing me from pushing to adopt Postiz for our organization — knowing that the output wasn't as good in this particular way as Buffer or other competitors. (This PR also fixes #667.)

Other information:

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

  • New Features

    • Added support for rich link previews in Bluesky, Facebook, and LinkedIn posts when sharing URLs without media attachments. Posts now display enhanced previews with title, description, and thumbnail where available.
    • Improved Facebook link preview reliability by prewarming Facebook's scraper for shared links.
    • Enhanced LinkedIn Page and personal post workflows to include OpenGraph-based link previews and thumbnails.
  • Bug Fixes

    • Improved error handling to ensure posts are still created even if link metadata or thumbnails cannot be fetched.

…ook. Uses OpenGraph scraping for LinkedIn, API link parameter for Facebook, and app.bsky.embed.external for Bluesky. Adds PostizBot user agents to metadata fetching to make it distinguishable to firewalls.
Copy link

vercel bot commented Jun 20, 2025

@jbenton is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Jun 20, 2025

Walkthrough

The changes introduce OpenGraph URL preview support for Bluesky, Facebook, and LinkedIn providers. New utility functions extract URLs from post text and fetch OpenGraph metadata. Posting logic is updated to detect URLs and, if no media is attached, generate and attach rich link previews using fetched metadata. Error handling is incorporated throughout.

Changes

File(s) Change Summary
.../social/bluesky.provider.ts Added OpenGraph metadata fetcher, URL extraction, and external embed creation for URL previews in posts without media. Modified post method to use these utilities.
.../social/facebook.provider.ts Added OpenGraph fetcher and URL extraction utilities. Enhanced post method to support link previews via Facebook's link parameter and prewarming scraper. Added prewarmFacebookScraper method.
.../social/linkedin.provider.ts, .../social/linkedin.page.provider.ts Added OpenGraph fetcher, URL extraction, and content entity creation for link previews. Updated post and payload creation methods to support link previews when no media is present.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Provider
    participant OpenGraphFetcher
    participant MediaUploader
    participant SocialAPI

    User->>Provider: Submit post with text (may include URL)
    Provider->>Provider: Extract URLs from text
    alt No media attached and URL found
        Provider->>OpenGraphFetcher: fetchOpenGraphData(url)
        OpenGraphFetcher-->>Provider: Return metadata (title, desc, image)
        alt Image present in metadata
            Provider->>MediaUploader: Upload image as thumbnail
            MediaUploader-->>Provider: Return image reference
        end
        Provider->>SocialAPI: Post content with external embed/link preview
    else Media attached or no URL
        Provider->>SocialAPI: Post content with media or plain text
    end
    SocialAPI-->>Provider: Return post response
    Provider-->>User: Return post result
Loading

Assessment against linked issues

Objective Addressed Explanation
Add URL preview feature to posts in Bluesky, loading OpenGraph info and removing URL from text (#667)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation

Suggested reviewers

  • nevo-david
  • egelhaus

Poem

A rabbit hops with glee,
"Now links have previews—oh, what a spree!
Titles and images, all in a row,
Posts on Bluesky, LinkedIn, Facebook now glow.
With OpenGraph magic, the world can see,
Just what’s behind every URL—yippee!"
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:201:49)

libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:201:49)

libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:201:49)

  • 1 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (2)
libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts (1)

18-69: Code duplication - extract to shared utilities.

This is another instance of the duplicated OpenGraph functions.

Please see the previous comment about extracting these functions to a shared utility module.

libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (1)

20-127: Code duplication - extract to shared utilities.

This is the fourth instance of the duplicated OpenGraph functions across the providers.

Please see the previous comment about extracting these functions to a shared utility module.

🧹 Nitpick comments (5)
libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (1)

380-390: Consider adding debug logging for URL processing.

The implementation correctly handles the priority of embeds (video > images > URLs). Consider adding debug logging when URLs are found but not used due to media presence.

       } else {
         // If no media, check for URLs to create external embeds
         const urls = extractUrls(post.message);
         if (urls.length > 0) {
+          console.log(`Creating external embed for URL: ${urls[0]}`);
           // Use the first URL found for the external embed
           const externalEmbed = await createExternalEmbed(agent, urls[0]);
           if (externalEmbed) {
             embed = externalEmbed;
           }
+        } else {
+          console.log('No URLs found in post message for external embed');
         }
       }
libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts (2)

67-67: Add missing newline before class declaration.

 }
 
+
 export class FacebookProvider extends SocialAbstract implements SocialProvider {

310-314: Consider improving URL removal logic to avoid awkward message formatting.

Simply removing the URL with replace() might leave awkward spacing or punctuation. For example, "Check out this link: https://example.com!" becomes "Check out this link: !".

-        // Remove URL from message text since we're putting it in the link field
-        const messageWithoutUrl = firstPost.message.replace(urls[0], '').trim();
+        // Remove URL from message text since we're putting it in the link field
+        let messageWithoutUrl = firstPost.message.replace(urls[0], '').trim();
+        // Clean up any awkward punctuation or spacing left behind
+        messageWithoutUrl = messageWithoutUrl
+          .replace(/:\s*$/, '') // Remove trailing colons
+          .replace(/\s+/g, ' ') // Normalize whitespace
+          .trim();
libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts (1)

71-71: Consider using union type for better type safety.

The function signature uses string literal for type but only 'company' is valid here.

-async function createLinkedInContentEntities(url: string, accessToken: string, personId: string, type: 'company', uploadPictureMethod: any): Promise<any> {
+async function createLinkedInContentEntities(
+  url: string, 
+  accessToken: string, 
+  personId: string, 
+  type: 'company' | 'personal', 
+  uploadPictureMethod: any
+): Promise<any> {
libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (1)

129-129: Add missing newline before class declaration.

 }
 
+
 export class LinkedinProvider extends SocialAbstract implements SocialProvider {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1642bc0 and 795099c.

📒 Files selected for processing (4)
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (5 hunks)
  • libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts (8 hunks)
  • libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts (2 hunks)
  • libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-and-publish
🔇 Additional comments (5)
libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (2)

221-224: LGTM!

The URL extraction implementation is clean and handles the edge case of no matches properly.


136-176: [web_search]

Does axios 1.7.7 support the maxContentLength configuration option to limit HTTP response size?
libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts (1)

389-407: Good implementation of Facebook-specific optimization.

The prewarm scraper method is well-implemented with proper error handling that doesn't fail the main post operation.

libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts (1)

359-369: Excellent use of inheritance and delegation pattern.

The override properly delegates to the parent class's enhanced functionality while specifying the 'company' type. This maintains code reuse and consistency.

libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (1)

657-669: Well-implemented URL detection and link preview support.

The implementation correctly checks for URLs only when no media is present and properly integrates with the existing post creation flow.

Comment on lines +191 to +203
const imageResponse = await axios.get(ogData.image, {
responseType: 'arraybuffer',
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; PostizBot/1.0; +https://postiz.com/)'
}
});
const imageBuffer = Buffer.from(imageResponse.data);

// Reduce image size if needed (Bluesky has limits)
const processedImage = await reduceImageBySize(ogData.image, 976);

const blob = await agent.uploadBlob(new Blob([processedImage]));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix inefficient double download of images.

The image is downloaded twice - once in this function and again in reduceImageBySize. Pass the buffer instead of the URL to avoid redundant network requests.

-        const processedImage = await reduceImageBySize(ogData.image, 976);
+        const processedImage = imageBuffer.length / 1024 > 976 
+          ? await reduceImageBySize(ogData.image, 976)
+          : imageBuffer;

Consider refactoring reduceImageBySize to accept a buffer as an alternative to URL to improve efficiency.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const imageResponse = await axios.get(ogData.image, {
responseType: 'arraybuffer',
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; PostizBot/1.0; +https://postiz.com/)'
}
});
const imageBuffer = Buffer.from(imageResponse.data);
// Reduce image size if needed (Bluesky has limits)
const processedImage = await reduceImageBySize(ogData.image, 976);
const blob = await agent.uploadBlob(new Blob([processedImage]));
const imageResponse = await axios.get(ogData.image, {
responseType: 'arraybuffer',
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; PostizBot/1.0; +https://postiz.com/)'
}
});
const imageBuffer = Buffer.from(imageResponse.data);
// Reduce image size if needed (Bluesky has limits)
- const processedImage = await reduceImageBySize(ogData.image, 976);
+ const processedImage = imageBuffer.length / 1024 > 976
+ ? await reduceImageBySize(ogData.image, 976)
+ : imageBuffer;
const blob = await agent.uploadBlob(new Blob([processedImage]));
🤖 Prompt for AI Agents
In libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
between lines 191 and 203, the image is downloaded twice: once directly with
axios and again inside reduceImageBySize using the URL. To fix this
inefficiency, refactor reduceImageBySize to accept an image buffer as input in
addition to a URL. Then, pass the already downloaded imageBuffer to
reduceImageBySize instead of the URL to avoid redundant network requests.

Comment on lines +14 to +66
interface OpenGraphData {
title?: string;
description?: string;
image?: string;
}

async function fetchOpenGraphData(url: string): Promise<OpenGraphData> {
try {
const response = await axios.get(url, {
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; PostizBot/1.0; +https://postiz.com/)'
}
});
const html = response.data;
const dom = new JSDOM(html);
const document = dom.window.document;

const getMetaContent = (property: string) => {
const element = document.querySelector(`meta[property="${property}"]`) ||
document.querySelector(`meta[name="${property}"]`);
return element?.getAttribute('content') || '';
};

const ogImage = getMetaContent('og:image');
let imageUrl = ogImage;

// Handle relative URLs for images
if (ogImage && !ogImage.startsWith('http')) {
try {
imageUrl = new URL(ogImage, url).href;
} catch {
imageUrl = ogImage; // Fallback to original if URL parsing fails
}
}

return {
title: getMetaContent('og:title') || getMetaContent('title') ||
document.querySelector('title')?.textContent || '',
description: getMetaContent('og:description') || getMetaContent('description') || '',
image: imageUrl || ''
};
} catch (error) {
console.error('Error fetching OpenGraph data:', error);
return {};
}
}

function extractUrls(text: string): string[] {
const urlRegex = /https?:\/\/[^\s/$.?#].[^\s]*/g;
return text.match(urlRegex) || [];
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Extract duplicated OpenGraph functions to a shared utility module.

The fetchOpenGraphData and extractUrls functions are duplicated across multiple providers. This violates the DRY principle.

Consider creating a shared utility file:

// libraries/nestjs-libraries/src/integrations/social/utils/opengraph.utils.ts
export interface OpenGraphData {
  title?: string;
  description?: string;
  image?: string;
}

export async function fetchOpenGraphData(url: string): Promise<OpenGraphData> {
  // ... implementation
}

export function extractUrls(text: string): string[] {
  // ... implementation
}

Then import and use these utilities in each provider instead of duplicating the code.

🤖 Prompt for AI Agents
In libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts lines
14 to 66, the functions fetchOpenGraphData and extractUrls are duplicated across
multiple providers, violating the DRY principle. To fix this, create a new
shared utility module at
libraries/nestjs-libraries/src/integrations/social/utils/opengraph.utils.ts
containing the OpenGraphData interface and the implementations of
fetchOpenGraphData and extractUrls. Then, remove these functions from
facebook.provider.ts and import them from the new utility module to reuse the
code.

return text.match(urlRegex) || [];
}

async function createLinkedInContentEntities(url: string, accessToken: string, personId: string, type: 'personal' | 'company', uploadPictureMethod: any): Promise<any> {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use union type and consider extracting shared LinkedIn utilities.

The type parameter should use a union type for better type safety. Also, this function is duplicated in linkedin.page.provider.ts.

-async function createLinkedInContentEntities(url: string, accessToken: string, personId: string, type: 'personal' | 'company', uploadPictureMethod: any): Promise<any> {
+// Consider moving to a shared LinkedIn utilities file
+async function createLinkedInContentEntities(
+  url: string,
+  accessToken: string,
+  personId: string,
+  type: 'personal' | 'company',
+  uploadPictureMethod: (filename: string, token: string, id: string, buffer: Buffer, type: 'personal' | 'company') => Promise<string>
+): Promise<any> {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function createLinkedInContentEntities(url: string, accessToken: string, personId: string, type: 'personal' | 'company', uploadPictureMethod: any): Promise<any> {
// Consider moving to a shared LinkedIn utilities file
async function createLinkedInContentEntities(
url: string,
accessToken: string,
personId: string,
type: 'personal' | 'company',
uploadPictureMethod: (filename: string, token: string, id: string, buffer: Buffer, type: 'personal' | 'company') => Promise<string>
): Promise<any> {
🤖 Prompt for AI Agents
In libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts at
line 73, update the type parameter from a string literal union to a proper
TypeScript union type for better type safety. Additionally, refactor by
extracting this function into a shared LinkedIn utilities module to avoid
duplication with linkedin.page.provider.ts, then import and use the shared
function in both places.

@altendorfme
Copy link
Contributor

Thanks!

@roshangm1
Copy link
Contributor

Definitely worth reviewing and merging into the main. @nevo-david

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add URL Preview Feature to Posts in Bluesky
3 participants