X bills a post containing a URL at a much higher rate than a plain post, and
its algorithm demotes link posts. The X version of a post now rewrites every
URL non-clickable (https://example.com/post becomes example(.)com/post):
scheme and www. dropped, every dot of the host replaced with (.).
Leaving a single dot intact would still leave a resolvable domain for X to
detect, so all of them are broken. A scheme or www. proves a token is a URL on
its own; a bare host only counts when its last label is a delegated TLD, which
is the one thing telling acme.com apart from Node.js. That check runs against
App\Support\LinkTlds, generated from the whole IANA root zone in every form a
TLD can appear in a post -- ASCII, punycode and the Unicode it decodes to --
because whatever X links is what X bills, so a hand-picked subset would leave
us paying for its gaps. If the regex engine bails out on pathological input the
original content is returned instead of crashing the publisher.
The transform lives in the Platform::X arm of ContentSanitizer, so it reaches
publishing and the app/API/MCP previews from one place and cannot touch any
other network. Off by default; opt in with X_DEFUSE_LINKS.
The editor counts characters and renders its preview client-side and cannot ask
the server on every keystroke, so the rewrite is mirrored in TypeScript. PHP
stays the source of truth: a parity test fails if the two TLD sets drift, and a
browser test drives the real editor so the mirror is covered rather than
assumed. Without it the composer promised text the network never receives.
Character limits now measure the text a reader will see: sanitized, then with
markup resolved away. Measuring the raw draft blocked saving posts that publish
fine and let through posts the network rejects, and counted the editor's HTML
toward the limit. Measuring the sanitized form alone would have counted
Telegram's escaped entities, rejecting messages Telegram accepts.
Empty content is handled once inside the sanitizer instead of by a guard
repeated at every call site.
- Extract estimatedDecodeMemory() + a MAX_DECODE_MEMORY_BYTES constant so optimizeImage (fallback) and the crop/fit guard (throw) share one estimate instead of duplicating the formula and threshold.
- Correct the cropFailureException docblock: it now covers download, crop, and story-fit failures, not just downloads.
- Add a Facebook crop process-failure test and an Instagram cropped-temp-leak test so the crop path matches the fit path's error coverage.
- Instagram carousel and Facebook multi-image crop tests now run as datasets
over 1:1 and 4:5, asserting each image's real cropped ratio (previously 1:1
only) — proving the chosen ratio flows through the multi-image paths.
- Add a Facebook test that a multi-image post aborts entirely (throws
FacebookPublishException) when one image can't be downloaded for cropping.
- CropsImageForAspectRatio: drop the per-publisher path-prefix argument; crops
from both platforms go to a single `social-crops/` directory (the folder has
no functional meaning — the platform fetches by URL and nothing reads it back;
UUID filenames prevent collisions).
- Close the IG/FB test asymmetry surfaced in review: Instagram single-image crop
now runs across 1:1/4:5/16:9 (dataset) and has a crop-download-failure test;
Facebook gains an explicit 'original' bypass test. Both platforms now cover the
same matrix (crop per ratio + uploaded-URL is the crop, original/no-meta
bypass, multi-image, download-failure exception).
Follow-up tracked in #83 (orphaned crops are never pruned from storage).
Facebook feed posts now have the same aspect ratio selector as Instagram
(1:1, 4:5, 16:9, Original), letting users control how their image is cropped
before publishing instead of leaving it to Facebook's auto-crop.
The Facebook Graph API has no crop/aspect-ratio parameter for organic Page
photo posts (image crops are ads-only) — Facebook displays the bytes it
receives at their native ratio. So, exactly like Instagram, the crop is done
server-side before upload.
- Extract the Instagram crop logic into a shared CropsImageForAspectRatio
concern (download -> crop -> store -> URL), with a per-publisher
cropFailureException hook. InstagramPublisher refactored to use it
(behaviour identical; existing tests unchanged).
- FacebookPublisher reads meta.aspect_ratio and crops single- and multi-image
feed posts (facebook-crops/ prefix). Reels/Stories are unaffected.
- FacebookSettings: aspect ratio picker on the Feed variant (default Original
-> no crop). ScheduleTab wires meta; FacebookPreview reflects the chosen
ratio. Adds posts.form.facebook.aspect.* in en/es/pt-BR.
Closes#69
Facebook Stories do not work reliably with images via the Graph API.
Align validation and publisher with video-only (like Reel), while
Instagram Story continues to accept image or video.
Co-authored-by: Cursor <cursoragent@cursor.com>
Multi-image posts were published as text-only because Laravel sent
attached_media as JSON; Facebook accepts message but drops attachments.
Use asForm() for all FacebookPublisher Graph API calls.
Co-authored-by: Cursor <cursoragent@cursor.com>
Production incident: a customer's Facebook Page post failed with 'The post
is empty. Please enter a message to share.' (error code 197) and ended up
with a contradictory DB state (status=published + error_message=set).
Three independent bugs were uncovered:
A. FacebookPublisher sends 'message'/'description' as null when the user
posts media without text. Graph API requires the key be omitted, not
null. Fixed in publishSingleImagePost, publishMultiImagePost,
publishVideoPost, publishReel.
B. markAsPublished/markAsFailed leak stale fields across transitions
(a published row could retain error_message from a prior failure,
vice-versa). Both transitions now explicitly clear the opposite
side's fields.
C. status='failed' was editable in the UI and the backend, so users
were re-clicking Publish, generating duplicate failure emails and
the contradictory state from bug B. The frontend isReadOnly check
and the UpdatePost backend guard now treat Published/PartiallyPublished/
Failed/Publishing as terminal. To retry, the user duplicates the post.
11 new tests guarantee these can't regress silently: FB payload shape
per content type, PostPlatform field-clearing on transitions, and the
terminal-status block at the controller level.
Five small fixes scoped to the publishReel method:
1. Replace generic \Exception on media download failure with a typed
FacebookPublishException(ServerError). The generic exception was
landing in the \Throwable catch in PublishToSocialPlatform with
category 'unknown', defeating the whole point of the social
exception hierarchy.
2. Replace handleApiError($startResponse) with a direct
FacebookPublishException throw when video_id/upload_url are missing.
The previous code passed a successful HTTP response into a method
built for error responses — fromApiResponse would fall into the
default arm and surface 'An unknown Facebook error occurred.'
ironically reintroducing the same bad UX we just spent the day
fixing.
3. Drop the four redundant Log::error calls before handleApiError.
FacebookPublishException::fromApiResponse already pulls the FB
error code/subcode/message into platformErrorCode + userMessage,
and the downstream catch in PublishToSocialPlatform::handle logs
the exception anyway (Nightwatch picks that up). Same pattern as
the X cleanup in PR #29.
4. Stream the upload body via fopen() resource instead of
file_get_contents(). Eliminates loading the whole video into memory
for large reels.
5. Replace \@unlink with unlink + Log::warning. Surfaces temp-file
cleanup failures instead of silently leaking files.
Tests:
- Strengthened the missing-upload_url test to assert the exception
message and class.
- Added a typed-exception test for the media-download failure path
(would have caught the regression where we used a generic
\Exception).
- Full suite green: 1505 passed, 2 skipped, 0 failed.
Previous attempt at the hosted-file flow (`file_url` in JSON body) hit
the rupload.facebook.com validator with HTTP 400:
'HeaderValuePredicate: Header Offset not convertable to unsigned long'
Facebook's rupload endpoint requires the `Offset` and `file_size` headers
regardless of whether the upload is local or hosted-file. The docs
describe the hosted-file path without them, but in practice rupload
rejects requests that lack them.
Switching to the well-documented local-file flow:
- Download the media to a temp file via Http sink (already a pattern
used in XPublisher for media downloads).
- POST raw bytes to upload_url with three headers:
- Authorization: OAuth {token}
- Offset: 0
- file_size: {actual bytes}
- Use mime_type from the media item as the Content-Type.
- Always cleanup the temp file in a finally block.
Tests updated to fake the media-download GET (returning bytes that the
publisher then re-uploads) and to assert on the Offset/file_size/
Authorization headers being present and correct. The existing
"cleans up temp files after reel upload" test now actually exercises
its assertion since this code path creates temp files again.
Full suite: 1504 passed, 2 skipped, 0 failed.
Production was failing every Facebook reel publish with the cryptic
'Video Upload Is Missing' / error_subcode 1363130. Root cause: our
'transfer' phase was making up its own API contract that doesn't exist.
The Reels publishing API (per Meta docs) is a 3-step flow:
1. start → POST /{page_id}/video_reels {upload_phase=start}
returns {video_id, upload_url}
2. transfer → POST {upload_url} on rupload.facebook.com
Header: Authorization: OAuth {token}
Body (JSON): {"file_url": "https://..."}
3. finish → POST /{page_id}/video_reels {upload_phase=finish, ...}
Our code was doing:
2 (broken) → POST /{video_id} on graph endpoint
Body: {video_file_chunk: '<some URL>', access_token: ...}
`video_file_chunk` is not a real parameter; the graph endpoint accepted
the request (returning 200) but nothing was actually uploaded, so the
finish phase reported 'Video was not uploaded'.
Changes:
- Capture upload_url from the start response and use it for transfer.
- POST to that upload_url with file_url in JSON body and
'Authorization: OAuth ...' header (the format docs.facebook.com
documents for the hosted-file flow).
- Bail with handleApiError if the start response is missing video_id
or upload_url so we don't silently no-op like before.
Tests:
- Existing 'can publish reel' test updated to include upload_url in the
start mock and assert the transfer call actually POSTs to rupload
with file_url + OAuth header (would have caught this bug before
shipping).
- New 'fails reel publish when start does not return upload_url' test
for the safety bail-out.
- Pre-existing 'cleans up temp files after reel upload' test updated
to match the new mock pattern.
Full suite green: 1504 passed, 2 skipped, 0 failed.
These tests use Http::fake, model factories, and DB — by Laravel/Pest
convention that's a feature test, not a unit test. Moving them to the
Feature suite to match the convention.
No code changes. Tests still pass: 1493 passed, 2 skipped, 0 failed.
2026-05-12 19:02:51 -03:00
Renamed from tests/Unit/Services/Social/FacebookPublisherTest.php (Browse further)