Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Attach link previews on LinkedIn and Facebook text posts (#367)

Paulo Castellano9c4c5d194cbf
diff --git a/app/Exceptions/Social/FacebookPublishException.php b/app/Exceptions/Social/FacebookPublishException.php
index ec277c4ac..258b59491 100644
--- a/app/Exceptions/Social/FacebookPublishException.php
+++ b/app/Exceptions/Social/FacebookPublishException.php
@@ -9,6 +9,30 @@ use Illuminate\Http\Client\Response;
class FacebookPublishException extends SocialPublishException
{
+ /**
+ * Graph codes that reject the Page feed `link` and leave the caption
+ * untouched: 1609005 (could not scrape the URL) and 1500 (invalid URL).
+ *
+ * @var list<string>
+ */
+ private const array LINK_REJECTION_CODES = ['1609005', '1500'];
+
+ /**
+ * Subcode under a code 200 "Permissions error" that means the `link`
+ * pointed at facebook.com, which Pages may not share through the API.
+ */
+ private const string FACEBOOK_URL_SUBCODE = '1609008';
+
+ public function __construct(
+ string $userMessage,
+ ErrorCategory $category,
+ ?string $platformErrorCode = null,
+ ?string $rawResponse = null,
+ public readonly ?string $platformErrorSubcode = null,
+ ) {
+ parent::__construct($userMessage, $category, $platformErrorCode, $rawResponse);
+ }
+
public static function fromApiResponse(mixed $response): static
{
/** @var Response $response */
@@ -66,9 +90,20 @@ class FacebookPublishException extends SocialPublishException
category: $category,
platformErrorCode: $errorCode !== null ? (string) $errorCode : null,
rawResponse: $rawResponse,
+ platformErrorSubcode: $errorSubcode !== null ? (string) $errorSubcode : null,
);
}
+ /**
+ * Whether Graph rejected the `link` rather than the post. The same caption
+ * publishes as plain text once the link is dropped.
+ */
+ public function rejectsLink(): bool
+ {
+ return in_array($this->platformErrorCode, self::LINK_REJECTION_CODES, true)
+ || ($this->platformErrorCode === '200' && $this->platformErrorSubcode === self::FACEBOOK_URL_SUBCODE);
+ }
+
public function platform(): string
{
return 'facebook';
diff --git a/app/Services/Brand/SafeHttpFetcher.php b/app/Services/Brand/SafeHttpFetcher.php
index 9c8428878..f5d4700c4 100644
--- a/app/Services/Brand/SafeHttpFetcher.php
+++ b/app/Services/Brand/SafeHttpFetcher.php
@@ -92,6 +92,56 @@ final class SafeHttpFetcher
}
}
+ /**
+ * Fetch a user-supplied URL without buffering more than the permitted body.
+ * Returns null for transport, HTTP, SSRF, redirect, or size failures.
+ */
+ public function tryGetBody(string $url, int $maxBytes): ?string
+ {
+ if ($maxBytes < 1) {
+ return null;
+ }
+
+ $stream = tmpfile();
+
+ if ($stream === false) {
+ return null;
+ }
+
+ try {
+ $response = $this->guardedRequest($url)
+ ->connectTimeout(3)
+ ->timeout(self::TIMEOUT_SECONDS)
+ // Guzzle owns and closes its sink; keep our temporary-file handle independent.
+ ->sink(stream_get_meta_data($stream)['uri'])
+ ->withOptions([
+ 'progress' => static function ($total, $downloaded) use ($maxBytes): void {
+ if ($total > $maxBytes || $downloaded > $maxBytes) {
+ throw new RuntimeException('Response body exceeded the maximum permitted size.');
+ }
+ },
+ ])
+ ->get($url);
+
+ if ($response->failed()) {
+ return null;
+ }
+
+ rewind($stream);
+ $body = stream_get_contents($stream, $maxBytes + 1);
+
+ if ($body === false || strlen($body) > $maxBytes) {
+ return null;
+ }
+
+ return $body;
+ } catch (ConnectionException|RuntimeException) {
+ return null;
+ } finally {
+ fclose($stream);
+ }
+ }
+
/**
* Guzzle allow_redirects options that re-run the SSRF guard on every hop.
* For callers that follow redirects on user-supplied URLs with methods/bodies
diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.php
index f20724178..a541df9f8 100644
--- a/app/Services/Social/AbstractLinkedInPublisher.php
+++ b/app/Services/Social/AbstractLinkedInPublisher.php
@@ -11,24 +11,38 @@ use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
+use App\Services\Brand\SafeHttpFetcher;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
+use App\Services\Social\LinkCard\LinkCardFetcher;
+use App\Services\Social\LinkCard\LinkCardMetadata;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
+use RuntimeException;
+use Throwable;
/**
* Shared LinkedIn publishing pipeline. The publish format follows the attached
- * media — a PDF becomes a document post, 2+ images a multi-image post, and
- * anything else (a single image/video or text only) a regular post. Subclasses
- * provide the author identity (member vs. company page) and its public URL.
+ * media: a PDF becomes a document post, two or more images a multi-image post,
+ * and a single image or video a media post. A text post with a link becomes an
+ * article, because the Posts API does not scrape URLs. Subclasses provide the
+ * author identity (member or company page) and its public URL.
*/
abstract class AbstractLinkedInPublisher
{
use HasSocialHttpClient;
+ /** Article title must be under 400 characters, description under 4,086. */
+ private const int ARTICLE_TITLE_MAX = 399;
+
+ private const int ARTICLE_DESCRIPTION_MAX = 4085;
+
+ private const int ARTICLE_THUMB_TIMEOUT_SECONDS = 10;
+
private string $apiVersion = '202601';
private string $accessToken;
@@ -110,7 +124,7 @@ abstract class AbstractLinkedInPublisher
$this->accessToken = $this->account->access_token;
return $this->dispatchByMedia($content, $postPlatform);
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
Log::error("{$this->label()} refresh failed during retry", [
'account_id' => $this->account->id,
'error' => $e->getMessage(),
@@ -133,11 +147,122 @@ abstract class AbstractLinkedInPublisher
'altText' => $item->isImage() ? $item->altTextFor($this->platform()) : null,
], fn ($v) => $v !== null)];
}
+ } else {
+ $article = $this->articleContent($content);
+
+ if ($article !== null) {
+ $payload['content'] = ['article' => $article];
+ }
}
return $this->createPost($payload, 'post creation');
}
+ /**
+ * Article payload for the first link in a text-only post. Null when there is
+ * no link, the page has no title, or the scrape fails: the post still goes
+ * out as text. The thumbnail is optional.
+ *
+ * @return array{source: string, title: string, description?: string, thumbnail?: string}|null
+ */
+ private function articleContent(?string $content): ?array
+ {
+ $card = filled($content) ? $this->articleCard($content) : null;
+
+ if ($card === null || blank($card->title)) {
+ return null;
+ }
+
+ return array_filter([
+ 'source' => $card->uri,
+ 'title' => Str::limit($card->title, self::ARTICLE_TITLE_MAX, ''),
+ 'description' => Str::limit($card->description, self::ARTICLE_DESCRIPTION_MAX, ''),
+ 'thumbnail' => $this->uploadArticleThumbnail($card),
+ ], filled(...));
+ }
+
+ private function articleCard(string $content): ?LinkCardMetadata
+ {
+ try {
+ return app(LinkCardFetcher::class)->fetch($content);
+ } catch (Throwable $e) {
+ Log::warning("{$this->label()} link preview lookup failed", ['error' => $e->getMessage()]);
+
+ return null;
+ }
+ }
+
+ /**
+ * Image URN for the card's og:image, or null when there is no usable image.
+ * A dead token still propagates so the publish retry can refresh it.
+ */
+ private function uploadArticleThumbnail(LinkCardMetadata $card): ?string
+ {
+ if (blank($card->imageUrl)) {
+ return null;
+ }
+
+ $tempFile = tempnam(sys_get_temp_dir(), 'li_article_');
+
+ if ($tempFile === false) {
+ return null;
+ }
+
+ try {
+ $this->downloadArticleThumbnail($card->imageUrl, $tempFile);
+
+ return $this->uploadLocalImage($tempFile);
+ } catch (TokenExpiredException $e) {
+ throw $e;
+ } catch (Throwable $e) {
+ Log::warning("{$this->label()} article thumbnail skipped", ['error' => $e->getMessage()]);
+
+ return null;
+ } finally {
+ @unlink($tempFile);
+ }
+ }
+
+ /**
+ * Redirects are not followed: the og:image URL is attacker-influenced and
+ * was only guarded against SSRF once.
+ */
+ private function downloadArticleThumbnail(string $url, string $tempFile): void
+ {
+ $maxBytes = MediaType::Image->maxSizeInBytes();
+
+ $response = app(SafeHttpFetcher::class)
+ ->guardedRequest($url, followRedirects: false)
+ ->timeout(self::ARTICLE_THUMB_TIMEOUT_SECONDS)
+ ->sink($tempFile)
+ ->withOptions([
+ 'progress' => static function ($total, $downloaded) use ($maxBytes): void {
+ if ($total > $maxBytes || $downloaded > $maxBytes) {
+ throw new RuntimeException('og:image exceeds the maximum image size');
+ }
+ },
+ ])
+ ->get($url);
+
+ if (! $response->successful()) {
+ throw new RuntimeException("og:image responded with HTTP {$response->status()}");
+ }
+
+ $size = filesize($tempFile);
+
+ if ($size === false || $size === 0) {
+ throw new RuntimeException('og:image is empty');
+ }
+
+ if ($size > $maxBytes) {
+ throw new RuntimeException('og:image exceeds the maximum image size');
+ }
+
+ if (MediaType::classify(File::mimeType($tempFile) ?: '') !== MediaType::Image) {
+ throw new RuntimeException('og:image is not an image');
+ }
+ }
+
private function publishCarousel(?string $content, $media): array
{
$images = [];
@@ -260,6 +385,51 @@ abstract class AbstractLinkedInPublisher
}
private function uploadImage($mediaItem): ?string
+ {
+ $tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
+
+ if ($tempFile === false) {
+ throw new LinkedInPublishException(
+ userMessage: "Could not prepare the image for {$this->label()}. Please try again.",
+ category: ErrorCategory::ServerError,
+ );
+ }
+
+ try {
+ $this->downloadToTempFile($mediaItem->url, $tempFile);
+
+ return $this->uploadLocalImage($tempFile);
+ } finally {
+ @unlink($tempFile);
+ }
+ }
+
+ /**
+ * Upload an image already on disk, re-encoded for LinkedIn first. GIFs are
+ * sent as they are so the animation survives. The caller owns the given
+ * file; the optimized copy is removed here.
+ */
+ private function uploadLocalImage(string $path): string
+ {
+ $mime = File::mimeType($path) ?: '';
+
+ if (MediaType::classify($mime) !== MediaType::Image || MediaType::isGif($mime)) {
+ return $this->uploadImageFile($path);
+ }
+
+ $optimized = app(MediaOptimizer::class)->optimizeImage($path, $this->platform());
+
+ try {
+ return $this->uploadImageFile($optimized);
+ } finally {
+ @unlink($optimized);
+ }
+ }
+
+ /**
+ * Initialize a LinkedIn image upload and PUT the bytes already on disk.
+ */
+ private function uploadImageFile(string $path): string
{
$initResponse = $this->getHttpClient()
->post("{$this->baseUrl()}/rest/images?action=initializeUpload", [
@@ -275,45 +445,37 @@ abstract class AbstractLinkedInPublisher
$uploadUrl = data_get($initData, 'value.uploadUrl');
$imageUrn = data_get($initData, 'value.image');
- if (! $uploadUrl || ! $imageUrn) {
+ if (! is_string($uploadUrl) || $uploadUrl === '' || ! is_string($imageUrn) || $imageUrn === '') {
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the image upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
- $tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
+ $stream = fopen($path, 'r');
- try {
- $this->downloadToTempFile($mediaItem->url, $tempFile);
-
- $detectedMime = File::mimeType($tempFile) ?: '';
- if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {
- $optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, $this->platform());
- @unlink($tempFile);
- $tempFile = $optimizedPath;
- }
-
- $stream = fopen($tempFile, 'r');
-
- $uploadResponse = Http::withToken($this->accessToken)
- ->withHeaders(['Content-Type' => 'application/octet-stream'])
- ->withBody($stream, 'application/octet-stream')
- ->put($uploadUrl);
+ if ($stream === false) {
+ throw new LinkedInPublishException(
+ userMessage: "Could not read the image for {$this->label()}. Please try again.",
+ category: ErrorCategory::ServerError,
+ );
+ }
- if (is_resource($stream)) {
- fclose($stream);
- }
+ $uploadResponse = Http::withToken($this->accessToken)
+ ->withHeaders(['Content-Type' => 'application/octet-stream'])
+ ->withBody($stream, 'application/octet-stream')
+ ->put($uploadUrl);
- if ($uploadResponse->failed()) {
- Log::error("{$this->label()} image upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);
- $this->handleApiError($uploadResponse);
- }
+ if (is_resource($stream)) {
+ fclose($stream);
+ }
- return $imageUrn;
- } finally {
- @unlink($tempFile);
+ if ($uploadResponse->failed()) {
+ Log::error("{$this->label()} image upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);
+ $this->handleApiError($uploadResponse);
}
+
+ return $imageUrn;
}
private function uploadVideo($mediaItem): ?string
diff --git a/app/Services/Social/FacebookPublisher.php b/app/Services/Social/FacebookPublisher.php
index b9faf1839..c62bc57b6 100644
--- a/app/Services/Social/FacebookPublisher.php
+++ b/app/Services/Social/FacebookPublisher.php
@@ -15,6 +15,7 @@ use App\Models\PostPlatform;
use App\Services\Social\Concerns\CropsImageForAspectRatio;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Meta\GraphError;
+use App\Support\FacebookLinkPreview;
use Closure;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
@@ -101,14 +102,60 @@ class FacebookPublisher
);
}
- $response = $this->postToGraph("{$pageId}/feed", [
- 'message' => $content,
- 'access_token' => $accessToken,
- ], 'text post');
+ $link = FacebookLinkPreview::url($content);
+
+ $response = $link === null
+ ? $this->postTextToFeed($pageId, $accessToken, $content, null)
+ : $this->postTextWithLink($pageId, $accessToken, $content, $link);
return $this->feedPostResult(data_get($response->json(), 'id'));
}
+ /**
+ * Facebook can reject the link and not the post: 1609005 (scrape failed),
+ * 1500 (invalid URL) or 200/1609008 (facebook.com URL). The caption
+ * published as plain text before `link` existed, so on those codes the
+ * card is dropped and the text is posted once more. Any other error fails
+ * the post. The first attempt stays quiet in the log because only the
+ * outcome of the retry says whether the publish failed.
+ */
+ private function postTextWithLink(string $pageId, string $accessToken, string $content, string $link): Response
+ {
+ try {
+ return $this->postTextToFeed($pageId, $accessToken, $content, $link, reportFailure: false);
+ } catch (FacebookPublishException $exception) {
+ if (! $exception->rejectsLink()) {
+ Log::error('Facebook text post failed', [
+ 'platform_error_code' => $exception->platformErrorCode,
+ 'body' => $this->redactResponseBody($exception->rawResponse ?? ''),
+ ]);
+
+ throw $exception;
+ }
+
+ Log::warning('Facebook rejected the link preview; publishing the text without it', [
+ 'platform_error_code' => $exception->platformErrorCode,
+ 'platform_error_subcode' => $exception->platformErrorSubcode,
+ ]);
+ }
+
+ return $this->postTextToFeed($pageId, $accessToken, $content, null);
+ }
+
+ /**
+ * A text post carries `link` when the caption contains a URL. Facebook does
+ * not unfurl a URL left only in `message`; the Page Feed `link` field is
+ * what makes it scrape Open Graph and render the preview.
+ */
+ private function postTextToFeed(string $pageId, string $accessToken, string $content, ?string $link, bool $reportFailure = true): Response
+ {
+ return $this->postToGraph("{$pageId}/feed", [
+ 'message' => $content,
+ 'access_token' => $accessToken,
+ ...$this->optionalField('link', $link),
+ ], 'text post', $reportFailure);
+ }
+
/**
* @return array{id: mixed, url: string}
*/
@@ -464,7 +511,7 @@ class FacebookPublisher
*
* @param array<string, string> $payload
*/
- private function postToGraph(string $path, array $payload, string $label): Response
+ private function postToGraph(string $path, array $payload, string $label, bool $reportFailure = true): Response
{
$response = $this->reachOrRetry(
fn (): Response => $this->facebookHttp()->post("{$this->baseUrl}/{$path}", $payload),
@@ -472,10 +519,13 @@ class FacebookPublisher
);
if ($response->failed()) {
- Log::error("Facebook {$label} failed", [
- 'status' => $response->status(),
- 'body' => $this->redactResponseBody($response->body()),
- ]);
+ if ($reportFailure) {
+ Log::error("Facebook {$label} failed", [
+ 'status' => $response->status(),
+ 'body' => $this->redactResponseBody($response->body()),
+ ]);
+ }
+
$this->handleApiError($response);
}
diff --git a/app/Services/Social/LinkCard/LinkCardFetcher.php b/app/Services/Social/LinkCard/LinkCardFetcher.php
index d987cf42d..7d4d735ef 100644
--- a/app/Services/Social/LinkCard/LinkCardFetcher.php
+++ b/app/Services/Social/LinkCard/LinkCardFetcher.php
@@ -19,6 +19,9 @@ class LinkCardFetcher
/** Cards for a public URL are identical for everyone; cache briefly and globally. */
private const int CACHE_MINUTES = 10;
+ /** OpenGraph metadata should occur near the document head; never buffer an unbounded page. */
+ private const int MAX_HTML_BYTES = 2 * 1024 * 1024;
+
public function __construct(
private readonly SafeHttpFetcher $http = new SafeHttpFetcher,
private readonly OpenGraphExtractor $extractor = new OpenGraphExtractor,
@@ -46,13 +49,13 @@ class LinkCardFetcher
private function build(string $url): ?LinkCardMetadata
{
- $response = $this->http->tryGet($url);
+ $html = $this->http->tryGetBody($url, self::MAX_HTML_BYTES);
- if ($response === null) {
+ if ($html === null) {
return null;
}
- $meta = $this->extractor->extract($response->body(), $url);
+ $meta = $this->extractor->extract($html, $url);
$title = data_get($meta, 'title');
$description = data_get($meta, 'description');
diff --git a/app/Support/FacebookLinkPreview.php b/app/Support/FacebookLinkPreview.php
new file mode 100644
index 000000000..b690838f6
--- /dev/null
+++ b/app/Support/FacebookLinkPreview.php
@@ -0,0 +1,47 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support;
+
+use Illuminate\Support\Str;
+
+/**
+ * First http(s) URL Facebook will accept as a Page feed `link`. facebook.com,
+ * fb.com and fb.me (and their subdomains) are skipped: the API rejects many of
+ * them and fails the whole post. The editor mirrors this in
+ * `resources/js/lib/facebookLinkPreview.ts`; the parity test keeps the two
+ * in step.
+ */
+final class FacebookLinkPreview
+{
+ /**
+ * @var list<string>
+ */
+ private const array OWNED_HOSTS = [
+ 'facebook.com',
+ '*.facebook.com',
+ 'fb.com',
+ '*.fb.com',
+ 'fb.me',
+ '*.fb.me',
+ ];
+
+ public static function url(string $text): ?string
+ {
+ return Str::matchAll(UrlDetector::URL_PATTERN, $text)
+ ->map(fn (string $raw): string => UrlDetector::trimTrailingPunctuation($raw))
+ ->first(fn (string $candidate): bool => ! self::isOwnedHost($candidate));
+ }
+
+ private static function isOwnedHost(string $url): bool
+ {
+ $host = parse_url($url, PHP_URL_HOST);
+
+ if (! is_string($host) || $host === '') {
+ return false;
+ }
+
+ return Str::is(self::OWNED_HOSTS, $host, ignoreCase: true);
+ }
+}
diff --git a/resources/js/components/posts/editor/PostEditorTabs.vue b/resources/js/components/posts/editor/PostEditorTabs.vue
index 9dcefb699..532528b83 100644
--- a/resources/js/components/posts/editor/PostEditorTabs.vue
+++ b/resources/js/components/posts/editor/PostEditorTabs.vue
@@ -78,28 +78,48 @@ const activeTab = defineModel<string>('activeTab', { required: true });
const emit = defineEmits<{
(e: 'toggle-platform', platformId: string): void;
(e: 'toggle-label', labelId: string): void;
- (e: 'update:platformMeta', platformId: string, meta: Record<string, any>): void;
- (e: 'update:platformContentType', platformId: string, contentType: string): void;
+ (
+ e: 'update:platformMeta',
+ platformId: string,
+ meta: Record<string, any>,
+ ): void;
+ (
+ e: 'update:platformContentType',
+ platformId: string,
+ contentType: string,
+ ): void;
}>();
const commentsTabRef = ref<InstanceType<typeof CommentsTab> | null>(null);
const previewablePlatforms = computed(() =>
- props.post.post_platforms.filter((pp) => props.selectedPlatformIds.includes(pp.id)),
+ props.post.post_platforms.filter((pp) =>
+ props.selectedPlatformIds.includes(pp.id),
+ ),
);
defineExpose({
- addCommentFromBroadcast: (comment: any) => commentsTabRef.value?.addCommentFromBroadcast(comment),
- registerMentionedUsers: (users: any) => commentsTabRef.value?.registerMentionedUsers(users),
+ addCommentFromBroadcast: (comment: any) =>
+ commentsTabRef.value?.addCommentFromBroadcast(comment),
+ registerMentionedUsers: (users: any) =>
+ commentsTabRef.value?.registerMentionedUsers(users),
});
</script>
<template>
- <Tabs v-model="activeTab" class="h-full flex flex-col">
- <TabsList class="mx-4 mt-4 hidden w-fit shrink-0 self-start lg:inline-flex">
- <TabsTrigger value="preview">{{ $t('posts.edit.tabs.preview') }}</TabsTrigger>
- <TabsTrigger value="schedule">{{ $t('posts.edit.tabs.channels') }}</TabsTrigger>
- <TabsTrigger value="comments">{{ $t('posts.edit.tabs.comments') }}</TabsTrigger>
+ <Tabs v-model="activeTab" class="flex h-full flex-col">
+ <TabsList
+ class="mx-4 mt-4 hidden w-fit shrink-0 self-start lg:inline-flex"
+ >
+ <TabsTrigger value="preview" data-testid="editor-tab-preview">{{
+ $t('posts.edit.tabs.preview')
+ }}</TabsTrigger>
+ <TabsTrigger value="schedule">{{
+ $t('posts.edit.tabs.channels')
+ }}</TabsTrigger>
+ <TabsTrigger value="comments">{{
+ $t('posts.edit.tabs.comments')
+ }}</TabsTrigger>
</TabsList>
<TabsContent value="preview" class="flex-1 overflow-y-auto">
@@ -113,7 +133,15 @@ defineExpose({
/>
</TabsContent>
- <TabsContent value="schedule" force-mount data-testid="channels-panel" :class="['flex-1 overflow-y-auto p-4', { hidden: activeTab !== 'schedule' }]">
+ <TabsContent
+ value="schedule"
+ force-mount
+ data-testid="channels-panel"
+ :class="[
+ 'flex-1 overflow-y-auto p-4',
+ { hidden: activeTab !== 'schedule' },
+ ]"
+ >
<ScheduleTab
:post-platforms="post.post_platforms"
:selected-platform-ids="selectedPlatformIds"
@@ -129,8 +157,13 @@ defineExpose({
:media="media"
@toggle-platform="(id) => emit('toggle-platform', id)"
@toggle-label="(id) => emit('toggle-label', id)"
- @update:platform-meta="(id, meta) => emit('update:platformMeta', id, meta)"
- @update:platform-content-type="(id, contentType) => emit('update:platformContentType', id, contentType)"
+ @update:platform-meta="
+ (id, meta) => emit('update:platformMeta', id, meta)
+ "
+ @update:platform-content-type="
+ (id, contentType) =>
+ emit('update:platformContentType', id, contentType)
+ "
/>
</TabsContent>
@@ -142,6 +175,5 @@ defineExpose({
:highlight-comment-id="initialHighlightCommentId"
/>
</TabsContent>
-
</Tabs>
</template>
diff --git a/resources/js/components/posts/previews/FacebookPreview.vue b/resources/js/components/posts/previews/FacebookPreview.vue
index a6ff12c77..be601ba80 100644
--- a/resources/js/components/posts/previews/FacebookPreview.vue
+++ b/resources/js/components/posts/previews/FacebookPreview.vue
@@ -1,11 +1,14 @@
<script setup lang="ts">
import { IconDots, IconPhoto } from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
-import { computed } from 'vue';
+import { computed, toRef } from 'vue';
+import LinkCard from '@/components/posts/previews/LinkCard.vue';
import PostMediaPreview from '@/components/posts/previews/PostMediaPreview.vue';
import { getInitials } from '@/composables/useInitials';
+import { useLinkCard } from '@/composables/useLinkCard';
import date from '@/date';
+import { facebookLinkPreviewUrl } from '@/lib/facebookLinkPreview';
import type { MediaItem } from '@/types/media';
interface SocialAccount {
@@ -36,6 +39,12 @@ const postedAtLabel = computed(() =>
date.formatFacebookPreview(props.postedAt, trans('common.just_now')),
);
+const { card: linkCard, loading: linkCardLoading } = useLinkCard(
+ toRef(props, 'content'),
+ toRef(props, 'media'),
+ facebookLinkPreviewUrl,
+);
+
// Content type helpers
const isReel = computed(() => props.contentType === 'facebook_reel');
const isStory = computed(() => props.contentType === 'facebook_story');
@@ -146,19 +155,29 @@ const truncatedContent = computed(() => {
</p>
</div>
- <!-- Post Media - Aspect ratio matches user's chosen crop -->
+ <!-- Link preview replaces the empty media well on a text post -->
<div
- v-if="feedAspectPadding !== null"
- class="relative w-full shrink-0 bg-black"
- :style="{ paddingBottom: `${feedAspectPadding}%` }"
- >
- <div class="absolute inset-0">
+ v-if="media.length === 0 && linkCardLoading"
+ class="mx-3 mb-2 h-24 shrink-0 animate-pulse rounded-lg bg-[#f0f2f5] dark:bg-[#3a3b3c]"
+ ></div>
+ <div v-else-if="media.length === 0 && linkCard" class="px-3">
+ <LinkCard :card="linkCard" />
+ </div>
+ <template v-else>
+ <!-- Post Media - Aspect ratio matches user's chosen crop -->
+ <div
+ v-if="feedAspectPadding !== null"
+ class="relative w-full shrink-0 bg-black"
+ :style="{ paddingBottom: `${feedAspectPadding}%` }"
+ >
+ <div class="absolute inset-0">
+ <PostMediaPreview :media="media" v-bind="feedMediaProps" />
+ </div>
+ </div>
+ <div v-else class="flex-1 relative bg-black min-h-0">
<PostMediaPreview :media="media" v-bind="feedMediaProps" />
</div>
- </div>
- <div v-else class="flex-1 relative bg-black min-h-0">
- <PostMediaPreview :media="media" v-bind="feedMediaProps" />
- </div>
+ </template>
<!-- Reactions Bar -->
<div
diff --git a/resources/js/components/posts/previews/LinkCard.vue b/resources/js/components/posts/previews/LinkCard.vue
index d440cc53b..8e8c950f2 100644
--- a/resources/js/components/posts/previews/LinkCard.vue
+++ b/resources/js/components/posts/previews/LinkCard.vue
@@ -5,7 +5,10 @@ defineProps<{ card: LinkCard }>();
</script>
<template>
- <div class="mt-3 overflow-hidden rounded-xl border border-neutral-200 dark:border-neutral-700">
+ <div
+ data-testid="link-card"
+ class="mt-3 overflow-hidden rounded-xl border border-neutral-200 dark:border-neutral-700"
+ >
<img
v-if="card.image"
:src="card.image"
@@ -13,16 +16,19 @@ defineProps<{ card: LinkCard }>();
class="aspect-[1.91/1] w-full object-cover"
/>
<div class="px-3 py-2">
- <div class="text-[13px] text-neutral-500 dark:text-neutral-400">{{ card.domain }}</div>
+ <div class="text-[13px] text-neutral-500 dark:text-neutral-400">
+ {{ card.domain }}
+ </div>
<div
v-if="card.title"
- class="mt-0.5 text-[15px] font-semibold text-neutral-900 dark:text-neutral-100 line-clamp-2"
+ data-testid="link-card-title"
+ class="mt-0.5 line-clamp-2 text-[15px] font-semibold text-neutral-900 dark:text-neutral-100"
>
{{ card.title }}
</div>
<div
v-if="card.description"
- class="mt-0.5 text-[14px] text-neutral-500 dark:text-neutral-400 line-clamp-2"
+ class="mt-0.5 line-clamp-2 text-[14px] text-neutral-500 dark:text-neutral-400"
>
{{ card.description }}
</div>
diff --git a/resources/js/components/posts/previews/LinkedInPreview.vue b/resources/js/components/posts/previews/LinkedInPreview.vue
index 066d7c9e3..69066846e 100644
--- a/resources/js/components/posts/previews/LinkedInPreview.vue
+++ b/resources/js/components/posts/previews/LinkedInPreview.vue
@@ -1,6 +1,10 @@
<script setup lang="ts">
+import { toRef } from 'vue';
+
+import LinkCard from "@/components/posts/previews/LinkCard.vue";
import VideoPreview from "@/components/posts/previews/VideoPreview.vue";
import { getInitials } from '@/composables/useInitials';
+import { useLinkCard } from '@/composables/useLinkCard';
import { isDocumentMedia, isVideoMedia } from '@/composables/useMedia';
import type { MediaItem } from '@/types/media';
@@ -19,7 +23,12 @@ interface Props {
media: MediaItem[];
}
-defineProps<Props>();
+const props = defineProps<Props>();
+
+const { card: linkCard, loading: linkCardLoading } = useLinkCard(
+ toRef(props, 'content'),
+ toRef(props, 'media'),
+);
</script>
<template>
@@ -67,6 +76,14 @@ defineProps<Props>();
</div>
</div>
+ <div
+ v-if="media.length === 0 && linkCardLoading"
+ class="mx-4 mb-3 h-24 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100 dark:border-[#38434f] dark:bg-[#38434f]"
+ ></div>
+ <div v-else-if="media.length === 0 && linkCard" class="px-4">
+ <LinkCard :card="linkCard" />
+ </div>
+
<!-- Media -->
<div v-if="media.length > 0">
<div class="grid" :class="{
diff --git a/resources/js/components/posts/previews/MastodonPreview.vue b/resources/js/components/posts/previews/MastodonPreview.vue
index f038fa80a..9f4472028 100644
--- a/resources/js/components/posts/previews/MastodonPreview.vue
+++ b/resources/js/components/posts/previews/MastodonPreview.vue
@@ -1,8 +1,10 @@
<script setup lang="ts">
-import { computed } from 'vue';
+import { computed, toRef } from 'vue';
+import LinkCard from "@/components/posts/previews/LinkCard.vue";
import VideoPreview from "@/components/posts/previews/VideoPreview.vue";
import { getInitials } from '@/composables/useInitials';
+import { useLinkCard } from '@/composables/useLinkCard';
import { isVideoMedia } from '@/composables/useMedia';
import date from '@/date';
import type { MediaItem } from '@/types/media';
@@ -26,6 +28,11 @@ interface Props {
const props = defineProps<Props>();
const postedAtLabel = computed(() => date.formatMastodonPreview(props.postedAt));
+
+const { card: linkCard, loading: linkCardLoading } = useLinkCard(
+ toRef(props, 'content'),
+ toRef(props, 'media'),
+);
</script>
<template>
@@ -58,6 +65,12 @@ const postedAtLabel = computed(() => date.formatMastodonPreview(props.postedAt))
{{ content }}
</div>
+ <div
+ v-if="media.length === 0 && linkCardLoading"
+ class="mb-3 h-24 animate-pulse rounded-xl border border-[#c9d4de] bg-neutral-100 dark:border-[#313543] dark:bg-[#313543]"
+ ></div>
+ <LinkCard v-else-if="media.length === 0 && linkCard" :card="linkCard" />
+
<!-- Media -->
<div v-if="media.length > 0" class="mb-3">
<div class="rounded-lg overflow-hidden" :class="{
diff --git a/resources/js/composables/useLinkCard.ts b/resources/js/composables/useLinkCard.ts
index 429a63196..6784c6186 100644
--- a/resources/js/composables/useLinkCard.ts
+++ b/resources/js/composables/useLinkCard.ts
@@ -13,50 +13,56 @@ export interface LinkCard {
image: string | null;
}
+const firstHttpUrl = (text: string): string | null =>
+ text.match(/https?:\/\/\S+/)?.[0] ?? null;
+
/**
- * Live link-preview card for the composer. Detects the first link in `content`
- * — a rough match is enough, because the backend re-detects it and returns the
- * exact, trimmed URL as `card.uri` — and resolves its OpenGraph card, but only
- * when no media is attached (media suppresses the link card on every platform).
+ * OpenGraph card for the link a platform will publish. Attached media hides it.
+ * The default is the first http(s) URL; pass a picker when the platform skips
+ * some hosts. The backend trims the URL and returns the card.
*/
-export const useLinkCard = (content: Ref<string>, media: Ref<MediaItem[]>) => {
+export const useLinkCard = (
+ content: Ref<string>,
+ media: Ref<MediaItem[]>,
+ selectUrl: (text: string) => string | null = firstHttpUrl,
+) => {
const card = ref<LinkCard | null>(null);
const loading = ref(false);
const http = useHttp<{ url: string }, LinkCard | null>({ url: '' });
+ let requestId = 0;
const url = computed(() =>
- media.value.length > 0 ? null : (content.value.match(/https?:\/\/\S+/)?.[0] ?? null),
+ media.value.length === 0 ? selectUrl(content.value) : null,
);
- const fetchCard = async (target: string): Promise<void> => {
- loading.value = true;
+ const loadCard = async (target: string): Promise<void> => {
+ const id = requestId;
+ http.url = target;
+
+ const data = await http.post(linkPreview.url()).catch(() => null);
- try {
- http.url = target;
- const data = await http.post(linkPreview.url());
- card.value = data?.uri ? data : null;
- } catch {
- card.value = null;
- } finally {
- loading.value = false;
+ // A slow response must not revive a removed link or overwrite a newer one.
+ if (id !== requestId) {
+ return;
}
+
+ card.value = data?.uri ? data : null;
+ loading.value = false;
};
- // The link went away (media attached, or URL removed) — drop the card at once.
+ // Drop the card the moment the URL changes so we never show A while B loads,
+ // and bump requestId so any in-flight response for the previous URL is ignored.
watch(url, (next) => {
- if (!next) {
- card.value = null;
- loading.value = false;
- }
+ requestId++;
+ card.value = null;
+ loading.value = next !== null;
});
- // A new link appeared — fetch it. `watch` only fires on change, so the same
- // URL is never re-requested; the debounce keeps it off every keystroke.
watchDebounced(
url,
(next) => {
if (next) {
- void fetchCard(next);
+ void loadCard(next);
}
},
{ debounce: 400, immediate: true },
diff --git a/resources/js/lib/facebookLinkPreview.ts b/resources/js/lib/facebookLinkPreview.ts
new file mode 100644
index 000000000..608645075
--- /dev/null
+++ b/resources/js/lib/facebookLinkPreview.ts
@@ -0,0 +1,31 @@
+/**
+ * Mirror of `App\Support\FacebookLinkPreview`. Facebook rejects many
+ * facebook.com, fb.com and fb.me links, so the preview skips the same hosts
+ * the publisher does.
+ */
+const FACEBOOK_HOSTS = ['facebook.com', 'fb.com', 'fb.me'] as const;
+
+const trimTrailingPunctuation = (url: string): string => {
+ const trimmed = url.replace(/[.,;:!?]$/, '');
+
+ return trimmed.endsWith(')') && !trimmed.includes('(')
+ ? trimmed.slice(0, -1)
+ : trimmed;
+};
+
+const isFacebookOwnedUrl = (url: string): boolean => {
+ try {
+ const host = new URL(url).hostname.toLowerCase();
+
+ return FACEBOOK_HOSTS.some(
+ (domain) => host === domain || host.endsWith(`.${domain}`),
+ );
+ } catch {
+ return false;
+ }
+};
+
+export const facebookLinkPreviewUrl = (text: string): string | null =>
+ [...text.matchAll(/https?:\/\/\S+/gu)]
+ .map(([raw]) => trimTrailingPunctuation(raw))
+ .find((url) => !isFacebookOwnedUrl(url)) ?? null;
diff --git a/tests/Browser/LinkCardPreviewTest.php b/tests/Browser/LinkCardPreviewTest.php
new file mode 100644
index 000000000..dad52fffb
--- /dev/null
+++ b/tests/Browser/LinkCardPreviewTest.php
@@ -0,0 +1,176 @@
+<?php
+
+declare(strict_types=1);
+
+use Amp\DeferredFuture;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Enums\UserWorkspace\Role;
+use App\Models\Post;
+use App\Models\PostPlatform;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\Http;
+use Pest\Browser\Execution;
+
+/**
+ * @param array<int, array<string, mixed>> $media
+ */
+function seedLinkCardPreviewPost(
+ Platform $platform,
+ string $content = 'Draft without a link',
+ array $media = [],
+): Post {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, ['role' => Role::Member->value]);
+ $user->update(['current_workspace_id' => $workspace->id]);
+
+ $account = SocialAccount::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'platform' => $platform,
+ 'scopes' => $platform->requiredPublishScopes(),
+ ]);
+
+ $post = Post::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'user_id' => $user->id,
+ 'content' => $content,
+ 'media' => $media,
+ ]);
+
+ PostPlatform::factory()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => $account->id,
+ 'platform' => $platform,
+ 'content_type' => match ($platform) {
+ Platform::Facebook => ContentType::FacebookPost,
+ Platform::LinkedIn => ContentType::LinkedInPost,
+ Platform::Mastodon => ContentType::MastodonPost,
+ default => throw new LogicException('Unsupported link-card browser test platform.'),
+ },
+ ]);
+
+ test()->actingAs($user);
+
+ return $post;
+}
+
+test('facebook linkedin and mastodon previews render fetched link cards', function (Platform $platform) {
+ $url = "https://93.184.216.34/{$platform->value}";
+ Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);
+
+ $post = seedLinkCardPreviewPost($platform, "Read {$url}");
+
+ visit(route('app.posts.edit', $post))
+ ->click('@editor-tab-preview')
+ ->assertSee('Article card')
+ ->assertPresent('@link-card')
+ ->assertNoJavaScriptErrors();
+
+ Http::assertSentCount(1);
+})->with([
+ 'Facebook' => Platform::Facebook,
+ 'LinkedIn' => Platform::LinkedIn,
+ 'Mastodon' => Platform::Mastodon,
+]);
+
+test('removing a url removes its visible card', function () {
+ Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);
+ $post = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');
+
+ visit(route('app.posts.edit', $post))
+ ->click('@editor-tab-preview')
+ ->assertSee('Article card')
+ ->clear('textarea:not([readonly])')
+ ->assertMissing('@link-card')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a failed fetch clears the previous card and a later url can recover', function () {
+ Http::fake([
+ 'https://93.184.216.34/article' => Http::response('<meta property="og:title" content="Article card">'),
+ 'https://93.184.216.34/broken' => Http::response('', 500),
+ 'https://93.184.216.34/recovered' => Http::response('<meta property="og:title" content="Recovered card">'),
+ ]);
+ $post = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');
+ $page = visit(route('app.posts.edit', $post))
+ ->click('@editor-tab-preview')
+ ->assertSee('Article card')
+ ->fill('textarea:not([readonly])', 'https://93.184.216.34/broken');
+
+ Execution::instance()->waitForExpectation(fn () => Http::assertSentCount(2));
+ $page->assertMissing('@link-card')
+ ->fill('textarea:not([readonly])', 'https://93.184.216.34/recovered')
+ ->assertSee('Recovered card')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a pending response cannot overwrite a newer card or revive a removed url', function (bool $removeUrl) {
+ $release = new DeferredFuture;
+ $started = false;
+ Http::fake(function ($request) use ($release, &$started) {
+ if ($request->url() === 'https://93.184.216.34/slow') {
+ $started = true;
+ $release->getFuture()->await();
+
+ return Http::response('<meta property="og:title" content="Stale card">');
+ }
+
+ return Http::response('<meta property="og:title" content="Current card">');
+ });
+
+ $post = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/slow');
+ $page = visit(route('app.posts.edit', $post))->click('@editor-tab-preview');
+
+ try {
+ Execution::instance()->waitForExpectation(function () use (&$started) {
+ expect($started)->toBeTrue();
+ });
+
+ $page->fill('textarea:not([readonly])', $removeUrl ? '' : 'https://93.184.216.34/current');
+
+ if (! $removeUrl) {
+ $page->assertSee('Current card');
+ }
+ } finally {
+ $release->complete();
+ }
+
+ $page->page()->waitForLoadState('networkidle');
+ $page->assertDontSee('Stale card');
+
+ if ($removeUrl) {
+ $page->assertMissing('@link-card');
+ } else {
+ $page->assertSee('Current card');
+ }
+
+ $page->assertNoJavaScriptErrors();
+})->with(['newer url' => false, 'removed url' => true]);
+
+test('attached media suppresses fetching until it is removed', function () {
+ Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);
+ $post = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article', [[
+ 'id' => 'image-1',
+ 'type' => 'image',
+ 'mime_type' => 'image/png',
+ 'path' => 'uploads/image.png',
+ 'url' => 'data:image/png;base64,'.base64_encode(file_get_contents(__DIR__.'/../fixtures/1x1.png')),
+ 'size' => 68,
+ ]]);
+
+ $page = visit(route('app.posts.edit', $post))
+ ->click('@editor-tab-preview')
+ ->assertPresent('@media-thumbnail')
+ ->assertMissing('@link-card');
+
+ Http::assertNothingSent();
+
+ $page->click('@media-remove')
+ ->assertSee('Article card')
+ ->assertNoJavaScriptErrors();
+
+ Http::assertSentCount(1);
+});
diff --git a/tests/Feature/Services/Social/FacebookPublisherTest.php b/tests/Feature/Services/Social/FacebookPublisherTest.php
index bfe06fe97..0484c5370 100644
--- a/tests/Feature/Services/Social/FacebookPublisherTest.php
+++ b/tests/Feature/Services/Social/FacebookPublisherTest.php
@@ -15,6 +15,7 @@ use App\Models\Workspace;
use App\Services\Social\FacebookPublisher;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Sleep;
use Intervention\Image\Drivers\Gd\Driver;
@@ -124,7 +125,8 @@ test('facebook publisher can publish text only post', function () {
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/feed')
- && $request['message'] === 'Check out this Facebook post!';
+ && $request['message'] === 'Check out this Facebook post!'
+ && ! array_key_exists('link', $request->data());
});
});
@@ -1210,5 +1212,227 @@ test('facebook publisher keeps links intact', function () {
$this->publisher->publish($this->postPlatform);
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
- && $request['message'] === 'New post: https://acme.com/blog');
+ && $request['message'] === 'New post: https://acme.com/blog'
+ && $request['link'] === 'https://acme.com/blog');
+});
+
+test('facebook publisher retries a text post without the link when the scrape fails', function () {
+ $this->post->update(['content' => 'Read https://example.com/post today']);
+
+ Http::fake([
+ '*/page_123/feed' => Http::sequence()
+ ->push(['error' => ['message' => 'There was a problem scraping the URL.', 'code' => 1609005]], 400)
+ ->push(['id' => 'page_123_post_456'], 200),
+ ]);
+
+ $result = $this->publisher->publish($this->postPlatform);
+
+ expect($result['id'])->toBe('page_123_post_456');
+
+ $feed = collect(Http::recorded())
+ ->map(fn (array $pair) => $pair[0])
+ ->filter(fn ($request) => str_contains($request->url(), '/page_123/feed'))
+ ->values();
+
+ expect($feed)->toHaveCount(2)
+ ->and($feed[0]['link'])->toBe('https://example.com/post')
+ ->and($feed[1]->data())->not->toHaveKey('link')
+ ->and($feed[1]['message'])->toBe('Read https://example.com/post today');
+});
+
+test('facebook publisher does not log an error when the rejected link is published without it', function () {
+ $this->post->update(['content' => 'Read https://example.com/post today']);
+
+ Log::spy();
+
+ Http::fake([
+ '*/page_123/feed' => Http::sequence()
+ ->push(['error' => ['message' => 'There was a problem scraping the URL.', 'code' => 1609005]], 400)
+ ->push(['id' => 'page_123_post_456'], 200),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Log::shouldHaveReceived('warning')->once();
+ Log::shouldNotHaveReceived('error');
+});
+
+test('facebook publisher logs an error when a text post fails for a reason other than the link', function () {
+ $this->post->update(['content' => 'Read https://example.com/post']);
+
+ Log::spy();
+
+ Http::fake([
+ '*/page_123/feed' => Http::response([
+ 'error' => ['message' => 'Duplicate post', 'code' => 506],
+ ], 400),
+ ]);
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(FacebookPublishException::class);
+
+ Log::shouldHaveReceived('error')->once();
+ Log::shouldNotHaveReceived('warning');
+});
+
+test('facebook publisher does not drop the link on an unrelated feed error', function () {
+ $this->post->update(['content' => 'Read https://example.com/post']);
+
+ Http::fake([
+ '*/page_123/feed' => Http::response([
+ 'error' => ['message' => 'Duplicate post', 'code' => 506],
+ ], 400),
+ ]);
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(FacebookPublishException::class);
+
+ Http::assertSentCount(1);
+});
+
+test('facebook publisher does not send a facebook-owned url as the link', function (string $url) {
+ $this->post->update(['content' => "See {$url}"]);
+
+ Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
+
+ $result = $this->publisher->publish($this->postPlatform);
+
+ expect($result['id'])->toBe('page_123_post_456');
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
+ && $request['message'] === "See {$url}"
+ && ! array_key_exists('link', $request->data()));
+
+ Http::assertSentCount(1);
+})->with([
+ 'www' => 'https://www.facebook.com/somepage',
+ 'mobile' => 'https://m.facebook.com/somepage',
+ 'apex' => 'https://facebook.com/events/1',
+ 'fb.com' => 'https://fb.com/somepage',
+ 'fb.me' => 'https://fb.me/abc',
+ 'subdomain' => 'https://l.facebook.com/l.php?u=https://example.com',
+]);
+
+test('facebook publisher uses the first url that facebook can preview', function () {
+ $this->post->update(['content' => 'See https://www.facebook.com/page and https://example.com/post.']);
+
+ Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
+ && $request['message'] === 'See https://www.facebook.com/page and https://example.com/post.'
+ && $request['link'] === 'https://example.com/post');
+});
+
+test('facebook publisher still attaches a link on a host that only looks like facebook', function () {
+ $this->post->update(['content' => 'See https://notfacebook.com/post']);
+
+ Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
+ && $request['link'] === 'https://notfacebook.com/post');
+});
+
+test('facebook publisher retries without the link when facebook rejects the url', function (array $error) {
+ $this->post->update(['content' => 'Read https://example.com/post today']);
+
+ Http::fake([
+ '*/page_123/feed' => Http::sequence()
+ ->push(['error' => $error], 400)
+ ->push(['id' => 'page_123_post_456'], 200),
+ ]);
+
+ $result = $this->publisher->publish($this->postPlatform);
+
+ expect($result['id'])->toBe('page_123_post_456');
+
+ $feed = collect(Http::recorded())
+ ->map(fn (array $pair) => $pair[0])
+ ->filter(fn ($request) => str_contains($request->url(), '/page_123/feed'))
+ ->values();
+
+ expect($feed)->toHaveCount(2)
+ ->and($feed[0]['link'])->toBe('https://example.com/post')
+ ->and($feed[1]->data())->not->toHaveKey('link');
+})->with([
+ 'invalid url' => [['message' => 'The url you supplied is invalid', 'code' => 1500]],
+ 'facebook.com link' => [['message' => 'Permissions error', 'code' => 200, 'error_subcode' => 1609008]],
+]);
+
+test('facebook publisher does not drop the link on a permissions error without the facebook-url subcode', function () {
+ $this->post->update(['content' => 'Read https://example.com/post']);
+
+ Http::fake([
+ '*/page_123/feed' => Http::response([
+ 'error' => ['message' => 'Permissions error', 'code' => 200],
+ ], 400),
+ ]);
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(FacebookPublishException::class);
+
+ Http::assertSentCount(1);
+});
+
+test('facebook publisher fails the post when the retry without the link is rejected too', function () {
+ $this->post->update(['content' => 'Read https://example.com/post']);
+
+ Log::spy();
+
+ Http::fake([
+ '*/page_123/feed' => Http::sequence()
+ ->push(['error' => ['message' => 'There was a problem scraping the URL.', 'code' => 1609005]], 400)
+ ->push(['error' => ['message' => 'Duplicate post', 'code' => 506]], 400),
+ ]);
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(FacebookPublishException::class, 'Duplicate post detected. Please modify content.');
+
+ Http::assertSentCount(2);
+ Log::shouldHaveReceived('warning')->once();
+ Log::shouldHaveReceived('error')->once();
+});
+
+test('facebook publisher does not retry a text post with a link when the token is dead', function () {
+ $this->post->update(['content' => 'Read https://example.com/post']);
+
+ Http::fake([
+ '*/page_123/feed' => Http::response([
+ 'error' => ['message' => 'Invalid OAuth access token.', 'code' => 190],
+ ], 400),
+ ]);
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(TokenExpiredException::class);
+
+ Http::assertSentCount(1);
+});
+
+test('facebook publisher does not attach a link card when the post has media', function () {
+ $this->post->update([
+ 'content' => 'Read https://example.com/post',
+ 'media' => [[
+ 'id' => 'test-media-id',
+ 'path' => 'media/2026-01/image.jpg',
+ 'url' => 'https://example.com/media/2026-01/image.jpg',
+ 'mime_type' => 'image/jpeg',
+ 'original_filename' => 'image.jpg',
+ ]],
+ ]);
+
+ Http::fake([
+ '*/page_123/photos' => Http::response([
+ 'id' => 'photo_123',
+ 'post_id' => 'page_123_photo_post_456',
+ ], 200),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/page_123/feed'));
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/photos')
+ && ! array_key_exists('link', $request->data()));
});
diff --git a/tests/Feature/Services/Social/LinkCard/LinkCardFetcherTest.php b/tests/Feature/Services/Social/LinkCard/LinkCardFetcherTest.php
index ca024fdf6..61c372ede 100644
--- a/tests/Feature/Services/Social/LinkCard/LinkCardFetcherTest.php
+++ b/tests/Feature/Services/Social/LinkCard/LinkCardFetcherTest.php
@@ -43,6 +43,14 @@ test('returns null when the page has no title or description', function () {
expect(app(LinkCardFetcher::class)->fetch('see https://example.com'))->toBeNull();
});
+test('returns null when the page exceeds the html download limit', function () {
+ Http::fake([
+ 'https://example.com' => Http::response(str_repeat('x', (2 * 1024 * 1024) + 1), 200),
+ ]);
+
+ expect(app(LinkCardFetcher::class)->fetch('see https://example.com'))->toBeNull();
+});
+
test('caches the result so a repeated url is fetched once', function () {
Http::fake([
'https://example.com' => Http::response(
diff --git a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
index 52f3e65c1..43cd85911 100644
--- a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
+++ b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
@@ -10,6 +10,8 @@ use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use App\Services\Social\LinkCard\LinkCardFetcher;
+use App\Services\Social\LinkCard\LinkCardMetadata;
use App\Services\Social\LinkedInPagePublisher;
use Illuminate\Support\Facades\Http;
@@ -443,6 +445,8 @@ test('linkedin page publisher keeps links intact', function () {
$this->post->update(['content' => 'New post: https://acme.com/blog']);
+ $this->mock(LinkCardFetcher::class)->shouldReceive('fetch')->once()->andReturn(null);
+
Http::fake([
config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [
'x-restli-id' => 'urn:li:share:1234567890',
@@ -454,3 +458,30 @@ test('linkedin page publisher keeps links intact', function () {
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& $request['commentary'] === 'New post: https://acme.com/blog');
});
+
+test('linkedin page publisher sends the article card under the organization', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: null,
+ ));
+
+ Http::fake([
+ config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:orgArticle',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
+ && $request['author'] === 'urn:li:organization:123456'
+ && $request['content']['article']['source'] === 'https://example.com/article'
+ && $request['content']['article']['title'] === 'The Article');
+});
diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.php
index efa4347cf..595bb5d5e 100644
--- a/tests/Feature/Services/Social/LinkedInPublisherTest.php
+++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php
@@ -11,6 +11,9 @@ use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use App\Services\Media\MediaOptimizer;
+use App\Services\Social\LinkCard\LinkCardFetcher;
+use App\Services\Social\LinkCard\LinkCardMetadata;
use App\Services\Social\LinkedInPublisher;
use Illuminate\Support\Facades\Http;
@@ -59,7 +62,8 @@ test('linkedin publisher can publish text-only post', function () {
return str_contains($request->url(), '/rest/posts')
&& $request['author'] === 'urn:li:person:abc123xyz'
&& $request['commentary'] === 'Hello from LinkedIn!'
- && $request['visibility'] === 'PUBLIC';
+ && $request['visibility'] === 'PUBLIC'
+ && ! isset($request['content']);
});
});
@@ -1151,6 +1155,8 @@ test('linkedin publisher keeps links intact', function () {
$this->post->update(['content' => 'New post: https://trypost.it/blog']);
+ $this->mock(LinkCardFetcher::class)->shouldReceive('fetch')->once()->andReturn(null);
+
Http::fake([
config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
'x-restli-id' => 'urn:li:share:1234567890',
@@ -1160,5 +1166,455 @@ test('linkedin publisher keeps links intact', function () {
$this->publisher->publish($this->postPlatform);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
- && $request['commentary'] === 'New post: https://trypost.it/blog');
+ && $request['commentary'] === 'New post: https://trypost.it/blog'
+ && ! isset($request['content']));
+});
+
+test('linkedin publisher sends an article card for a text post that contains a link', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article today.']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: null,
+ ));
+
+ Http::fake([
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:article1',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $request['commentary'] === 'Read this https://example.com/article today.'
+ && $article['source'] === 'https://example.com/article'
+ && $article['title'] === 'The Article'
+ && $article['description'] === 'A great read'
+ && ! isset($article['thumbnail']);
+ });
+});
+
+test('linkedin publisher skips the article card when the page has no title', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: ' ',
+ description: 'Only a description',
+ imageUrl: null,
+ ));
+
+ Http::fake([
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:notitle',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
+ && ! isset($request['content']));
+});
+
+test('linkedin publisher prefers attached media over a link card', function () {
+ $this->post->update([
+ 'content' => 'see https://example.com/article',
+ 'media' => [[
+ 'id' => 'test-media-id',
+ 'path' => 'media/2026-01/test-image.jpg',
+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',
+ 'mime_type' => 'image/jpeg',
+ 'original_filename' => 'test.jpg',
+ ]],
+ ]);
+
+ $this->mock(LinkCardFetcher::class)->shouldNotReceive('fetch');
+
+ $uploadUrl = 'https://www.linkedin.com/dms/upload/v2/pic/0/C5622AQFake';
+
+ Http::fake(function ($request) use ($uploadUrl) {
+ $url = $request->url();
+
+ if (str_contains($url, '/rest/images')) {
+ return Http::response([
+ 'value' => [
+ 'uploadUrl' => $uploadUrl,
+ 'image' => 'urn:li:image:C5622AQFakeImageUrn',
+ ],
+ ], 200);
+ }
+
+ if ($url === $uploadUrl) {
+ return Http::response(null, 201);
+ }
+
+ if (str_contains($url, '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:mediawins']);
+ }
+
+ return Http::response('fake-image-content', 200);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
+ && isset($request['content']['media']['id'])
+ && ! isset($request['content']['article']));
+});
+
+test('linkedin publisher uploads the article thumbnail', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/card.jpg',
+ ));
+
+ $this->mock(MediaOptimizer::class)
+ ->shouldReceive('optimizeImage')
+ ->once()
+ ->andReturnUsing(fn () => tap(tempnam(sys_get_temp_dir(), 'li_thumb_'), fn ($path) => file_put_contents($path, 'thumb-bytes')));
+
+ $jpeg = linkedInJpegBytes();
+ $uploadUrl = 'https://www.linkedin.com/dms/upload/v2/pic/0/article-thumb';
+
+ Http::fake(function ($request) use ($uploadUrl, $jpeg) {
+ $url = $request->url();
+
+ if (str_contains($url, '/rest/images')) {
+ return Http::response([
+ 'value' => [
+ 'uploadUrl' => $uploadUrl,
+ 'image' => 'urn:li:image:articleThumb',
+ ],
+ ], 200);
+ }
+
+ if ($url === $uploadUrl) {
+ return Http::response(null, 201);
+ }
+
+ if (str_contains($url, '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:withthumb']);
+ }
+
+ return Http::response($jpeg, 200);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['thumbnail'] === 'urn:li:image:articleThumb'
+ && $article['source'] === 'https://example.com/article';
+ });
+});
+
+test('linkedin publisher still publishes the article when the thumbnail cannot be fetched', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/missing.jpg',
+ ));
+
+ Http::fake(function ($request) {
+ if (str_contains($request->url(), '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:nothumb']);
+ }
+
+ return Http::response('', 404);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['title'] === 'The Article'
+ && ! isset($article['thumbnail']);
+ });
+});
+
+test('linkedin publisher stops downloading an oversized article thumbnail', function () {
+ config()->set('trypost.media.max_size_mb.image', 1);
+
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/oversized.jpg',
+ ));
+
+ Http::fake(function ($request) {
+ if (str_contains($request->url(), '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:oversized']);
+ }
+
+ return Http::response(str_repeat('x', (1024 * 1024) + 1), 200, [
+ 'Content-Type' => 'image/jpeg',
+ 'Content-Length' => (string) ((1024 * 1024) + 1),
+ ]);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/images'));
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['title'] === 'The Article'
+ && ! isset($article['thumbnail']);
+ });
+});
+
+test('linkedin publisher publishes the text when the link preview lookup fails', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andThrow(new RuntimeException('scrape failed'));
+
+ Http::fake([
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:lookupfailed',
+ ]),
+ ]);
+
+ $result = $this->publisher->publish($this->postPlatform);
+
+ expect($result['id'])->toBe('urn:li:share:lookupfailed');
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
+ && $request['commentary'] === 'Read this https://example.com/article'
+ && ! isset($request['content']));
+});
+
+test('linkedin publisher blocks the article thumbnail when the image points at a private address', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'http://127.0.0.1/evil.jpg',
+ ));
+
+ Http::fake([
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:private',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['title'] === 'The Article'
+ && ! isset($article['thumbnail']);
+ });
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '127.0.0.1'));
+});
+
+test('linkedin publisher does not follow a redirect on the article thumbnail', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/card.jpg',
+ ));
+
+ Http::fake([
+ 'https://93.184.216.34/card.jpg' => Http::response('', 302, ['Location' => 'http://127.0.0.1/internal.jpg']),
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:noredirect',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['title'] === 'The Article'
+ && ! isset($article['thumbnail']);
+ });
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '127.0.0.1'));
});
+
+test('linkedin publisher trims the article title and description to what the api accepts', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: str_repeat('t', 500),
+ description: str_repeat('d', 5000),
+ imageUrl: null,
+ ));
+
+ Http::fake([
+ config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [
+ 'x-restli-id' => 'urn:li:share:trimmed',
+ ]),
+ ]);
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && mb_strlen($article['title']) === 399
+ && mb_strlen($article['description']) === 4085;
+ });
+});
+
+test('linkedin publisher skips the thumbnail when og:image does not point at an image', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->once()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/card.jpg',
+ ));
+
+ Http::fake(function ($request) {
+ if (str_contains($request->url(), '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:html']);
+ }
+
+ return Http::response('<html><body>Not an image</body></html>', 200, ['Content-Type' => 'text/html']);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/images'));
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $article['title'] === 'The Article'
+ && ! isset($article['thumbnail']);
+ });
+});
+
+test('linkedin publisher refreshes the token when the thumbnail upload is rejected', function () {
+ $this->post->update(['content' => 'Read this https://example.com/article']);
+
+ $this->mock(LinkCardFetcher::class)
+ ->shouldReceive('fetch')
+ ->twice()
+ ->andReturn(new LinkCardMetadata(
+ uri: 'https://example.com/article',
+ title: 'The Article',
+ description: 'A great read',
+ imageUrl: 'https://93.184.216.34/card.jpg',
+ ));
+
+ $this->mock(MediaOptimizer::class)
+ ->shouldReceive('optimizeImage')
+ ->twice()
+ ->andReturnUsing(fn () => tap(tempnam(sys_get_temp_dir(), 'li_thumb_'), fn ($path) => file_put_contents($path, 'thumb-bytes')));
+
+ $jpeg = linkedInJpegBytes();
+ $uploadUrl = 'https://www.linkedin.com/dms/upload/v2/pic/0/article-thumb';
+ $imageInitCalls = 0;
+
+ Http::fake(function ($request) use ($uploadUrl, $jpeg, &$imageInitCalls) {
+ $url = $request->url();
+
+ if (str_contains($url, '/rest/images')) {
+ return ++$imageInitCalls === 1
+ ? Http::response(['message' => 'Expired token'], 401)
+ : Http::response(['value' => ['uploadUrl' => $uploadUrl, 'image' => 'urn:li:image:afterRefresh']], 200);
+ }
+
+ if ($url === $uploadUrl) {
+ return Http::response(null, 201);
+ }
+
+ if (str_contains($url, '/oauth/v2/accessToken')) {
+ return Http::response(['access_token' => 'new-access-token', 'refresh_token' => 'new-refresh-token', 'expires_in' => 5184000], 200);
+ }
+
+ if (str_contains($url, '/rest/posts')) {
+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:refreshed']);
+ }
+
+ return Http::response($jpeg, 200);
+ });
+
+ $this->publisher->publish($this->postPlatform);
+
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/oauth/v2/accessToken'));
+ Http::assertSent(function ($request) {
+ $article = $request['content']['article'] ?? null;
+
+ return str_contains($request->url(), '/rest/posts')
+ && $request->hasHeader('Authorization', 'Bearer new-access-token')
+ && $article['thumbnail'] === 'urn:li:image:afterRefresh';
+ });
+});
+
+function linkedInJpegBytes(): string
+{
+ $image = imagecreatetruecolor(8, 8);
+ ob_start();
+ imagejpeg($image);
+ $bytes = ob_get_clean();
+ imagedestroy($image);
+
+ return $bytes === false ? '' : $bytes;
+}
diff --git a/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php b/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php
index f7394c8fd..d1f6a491b 100644
--- a/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php
+++ b/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php
@@ -125,6 +125,38 @@ test('unknown code maps to Unknown category with error message', function () {
->and($exception->userMessage)->toBe('An unexpected error occurred.');
});
+test('code 200 keeps the facebook-url subcode', function () {
+ $response = Http::response([
+ 'error' => [
+ 'message' => 'Permissions error',
+ 'type' => 'OAuthException',
+ 'code' => 200,
+ 'error_subcode' => 1609008,
+ ],
+ ], 400);
+
+ $fakeResponse = Http::fake(['*' => $response])->post('https://graph.facebook.com/test');
+
+ $exception = FacebookPublishException::fromApiResponse($fakeResponse);
+
+ expect($exception->platformErrorCode)->toBe('200')
+ ->and($exception->platformErrorSubcode)->toBe('1609008')
+ ->and($exception->userMessage)->toBe('Permissions error');
+});
+
+test('a link rejection is told apart from a failed post', function (array $error, bool $rejectsLink) {
+ $fakeResponse = Http::fake(['*' => Http::response(['error' => $error], 400)])
+ ->post('https://graph.facebook.com/test');
+
+ expect(FacebookPublishException::fromApiResponse($fakeResponse)->rejectsLink())->toBe($rejectsLink);
+})->with([
+ 'scrape failed' => [['message' => 'There was a problem scraping the URL.', 'code' => 1609005], true],
+ 'invalid url' => [['message' => 'The url you supplied is invalid', 'code' => 1500], true],
+ 'facebook.com link' => [['message' => 'Permissions error', 'code' => 200, 'error_subcode' => 1609008], true],
+ 'permissions error without the subcode' => [['message' => 'Permissions error', 'code' => 200], false],
+ 'duplicate post' => [['message' => 'Duplicate post', 'code' => 506], false],
+]);
+
test('subcode 463 throws TokenExpiredException', function () {
$response = Http::response([
'error' => [
diff --git a/tests/Unit/Services/Brand/SafeHttpFetcherTest.php b/tests/Unit/Services/Brand/SafeHttpFetcherTest.php
index 9f4983e54..a6b39d2b8 100644
--- a/tests/Unit/Services/Brand/SafeHttpFetcherTest.php
+++ b/tests/Unit/Services/Brand/SafeHttpFetcherTest.php
@@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Services\Brand\SafeHttpFetcher;
+use GuzzleHttp\Psr7\Utils;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
@@ -90,3 +91,57 @@ test('guardedRequest returns a PendingRequest for a public url', function () {
expect(app(SafeHttpFetcher::class)->guardedRequest('https://93.184.216.34/x'))
->toBeInstanceOf(PendingRequest::class);
});
+
+test('tryGetBody returns a body within the requested byte limit', function () {
+ Http::fake([
+ 'https://93.184.216.34/page' => Http::response('1234', 200),
+ ]);
+
+ expect(app(SafeHttpFetcher::class)->tryGetBody('https://93.184.216.34/page', 4))
+ ->toBe('1234');
+});
+
+test('tryGetBody cleans up when the transport closes its sink before failing', function () {
+ Http::fake(function ($request, array $options) {
+ $sink = $options['sink'];
+ $body = Utils::streamFor(
+ is_string($sink) ? Utils::tryFopen($sink, 'w+') : $sink,
+ );
+ $body->close();
+
+ throw new RuntimeException('Transport failed after closing the response body.');
+ });
+
+ expect(app(SafeHttpFetcher::class)->tryGetBody('https://93.184.216.34/page', 4))->toBeNull();
+});
+
+test('tryGetBody rejects a body larger than the requested byte limit', function () {
+ Http::fake([
+ 'https://93.184.216.34/page' => Http::response('12345', 200),
+ ]);
+
+ expect(app(SafeHttpFetcher::class)->tryGetBody('https://93.184.216.34/page', 4))
+ ->toBeNull();
+});
+
+test('tryGetBody aborts an oversized transfer and closes its temporary stream', function (int $total, int $downloaded) {
+ $stream = null;
+ $completed = false;
+
+ Http::fake(function ($request, array $options) use ($total, $downloaded, &$stream, &$completed) {
+ $stream = $options['sink'];
+ expect(is_file($stream))->toBeTrue();
+
+ $options['progress']($total, $downloaded);
+ $completed = true;
+
+ return Http::response('should never finish');
+ });
+
+ expect(app(SafeHttpFetcher::class)->tryGetBody('https://93.184.216.34/page', 4))->toBeNull()
+ ->and($completed)->toBeFalse()
+ ->and(file_exists($stream))->toBeFalse();
+})->with([
+ 'declared length' => [5, 0],
+ 'unknown length' => [0, 5],
+]);
diff --git a/tests/Unit/Support/FacebookLinkPreviewTest.php b/tests/Unit/Support/FacebookLinkPreviewTest.php
new file mode 100644
index 000000000..0d5972dd3
--- /dev/null
+++ b/tests/Unit/Support/FacebookLinkPreviewTest.php
@@ -0,0 +1,63 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Support\FacebookLinkPreview;
+use Symfony\Component\Process\Process;
+
+/**
+ * Captions the publisher and the editor must resolve to the same `link`.
+ * A null value means the post goes out as plain text.
+ *
+ * @return array<string, ?string>
+ */
+function facebookLinkPreviewCorpus(): array
+{
+ return [
+ 'no link here' => null,
+ 'Read https://example.com/post today' => 'https://example.com/post',
+ 'See https://example.com/post.' => 'https://example.com/post',
+ 'See https://example.com/post).' => 'https://example.com/post',
+ 'See https://www.facebook.com/page' => null,
+ 'See https://m.facebook.com/page' => null,
+ 'See https://facebook.com/events/1' => null,
+ 'See https://FB.com/page' => null,
+ 'See https://fb.me/abc' => null,
+ 'See https://l.facebook.com/l.php?u=https://example.com' => null,
+ 'See https://www.facebook.com/page and https://example.com/post.' => 'https://example.com/post',
+ 'See https://notfacebook.com/post' => 'https://notfacebook.com/post',
+ 'See https://example.com/a..' => 'https://example.com/a.',
+ ];
+}
+
+test('facebook link preview picks the url the page feed will accept', function () {
+ foreach (facebookLinkPreviewCorpus() as $text => $expected) {
+ expect(FacebookLinkPreview::url($text))->toBe($expected);
+ }
+});
+
+test('the editor picks the same facebook link as the publisher', function () {
+ $corpus = array_keys(facebookLinkPreviewCorpus());
+ $corpusPath = tempnam(sys_get_temp_dir(), 'fb_links');
+ file_put_contents($corpusPath, json_encode($corpus, JSON_THROW_ON_ERROR));
+
+ $process = new Process([
+ 'node',
+ '--experimental-strip-types',
+ base_path('tests/fixtures/facebook-link-preview-harness.js'),
+ resource_path('js/lib/facebookLinkPreview.ts'),
+ $corpusPath,
+ ]);
+ $process->run();
+
+ unlink($corpusPath);
+
+ if (! $process->isSuccessful()) {
+ $this->markTestSkipped('node is unavailable: '.$process->getErrorOutput());
+ }
+
+ $fromTypeScript = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
+ $fromPhp = array_map(fn (string $entry): ?string => FacebookLinkPreview::url($entry), $corpus);
+
+ expect(array_combine($corpus, $fromTypeScript))->toEqual(array_combine($corpus, $fromPhp));
+});
diff --git a/tests/fixtures/facebook-link-preview-harness.js b/tests/fixtures/facebook-link-preview-harness.js
new file mode 100644
index 000000000..13fc8ae8e
--- /dev/null
+++ b/tests/fixtures/facebook-link-preview-harness.js
@@ -0,0 +1,13 @@
+/**
+ * Runs `resources/js/lib/facebookLinkPreview.ts` over a corpus and prints the
+ * results as JSON, so the PHP parity test can diff it against
+ * `App\Support\FacebookLinkPreview`.
+ */
+import fs from 'node:fs';
+import { pathToFileURL } from 'node:url';
+
+const [modulePath, corpusPath] = process.argv.slice(2);
+const { facebookLinkPreviewUrl } = await import(pathToFileURL(modulePath).href);
+const corpus = JSON.parse(fs.readFileSync(corpusPath, 'utf8'));
+
+console.log(JSON.stringify(corpus.map((entry) => facebookLinkPreviewUrl(entry))));