trypost/tests/Feature/Services/Social/TikTokPublisherTest.php

1404 lines
51 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
Resume in-flight Instagram and TikTok publishes without duplicates (#281) * Improve asynchronous social publishing reliability * fix: resume asynchronous social publishes * fix: preserve publish checkpoints across retries * fix: harden resumable publish lifecycle * fix: clean retry resources on terminal failures * test: cover resumable social publishing edge cases * feat: add failed post retry command * chore: remove retry command ai rule * fix: require confirmation for post retries * chore: remove ai rules index * chore: remove ai social rule * refactor: clarify TikTok derivative path validation * refactor: simplify social publishing retries * refactor: further simplify social publishing retries * refactor: retry all failed post platforms * style: import throwable in social retries * refactor: decouple TikTok cleanup from image format * refactor: extract missing publish scopes * refactor: encapsulate missing scope failure * fix: resume failed publishes and treat Instagram rate limits as transient Keep TikTok/Instagram checkpoints on posts:retry so a manual retry does not start a duplicate remote post. Classify Meta BUC 400s on Instagram status polls as retryable via GraphError. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover resume paths and transient Instagram rate limits Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume posts:retry only for in-flight publish failures Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume posts:retry via ErrorCategory instead of string lists Co-authored-by: Cursor <cursoragent@cursor.com> * fix: handle Instagram PUBLISHED and EXPIRED container statuses Treat EXPIRED as a terminal server error so posts:retry starts over, and complete already-published containers without a second media_publish. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: recover published Instagram stories from /stories Stories are not on GET /{ig-user-id}/media. Resume a PUBLISHED story container from the stories edge so we do not bind a feed post id. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover Instagram EXPIRED retry and published recovery paths Co-authored-by: Cursor <cursoragent@cursor.com> * fix: stop guessing Instagram media ids from recent /media Co-authored-by: Cursor <cursoragent@cursor.com> * fix: checkpoint TikTok publish_id and keep in-flight photo derivatives Persist publish_id right after /init/ so a crash can resume without a second publish. Keep hosted photos while that id is resumable, including token expiry on status fetch; prune only after success or a confirmed remote failure. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover remaining TikTok in-flight derivative edge cases Guard the empty publish_id prune path, account guards without a checkpoint, and video status 401 after /init/. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor: map TikTok publish statuses with an official enum Use PublishStatus for status/fetch values from the Content Posting API. Keep only the documented cases, including FAILED as the terminal failure. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor: share in-flight publish checkpoint keys Read TikTok and Instagram resume state through one helper so publishers, posts:retry, and derivative cleanup agree on the same keys. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: retry Instagram media_publish after transient Graph failures A 500/code 2 after Meta already published left the job Failed as unknown. Treat that as still-processing so resume can confirm PUBLISHED instead of posting again. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume Instagram publish after dropped Graph connections A timeout or connection reset after Meta already published was marked unknown. Treat it as still-processing so resume can confirm PUBLISHED instead of posting again. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 18:34:53 +00:00
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\TikTokPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
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\TikTokPublisher;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->socialAccount = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => 'tiktok123',
'username' => 'tiktoker',
'token_expires_at' => now()->addDays(1),
]);
$this->post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'content' => 'Check out this TikTok video!',
]);
$this->postPlatform = PostPlatform::factory()->tiktok()->create([
'post_id' => $this->post->id,
'social_account_id' => $this->socialAccount->id,
'platform' => Platform::TikTok,
'content_type' => ContentType::TikTokVideo,
]);
$this->publisher = new TikTokPublisher;
$this->api = config('trypost.platforms.tiktok.api');
});
test('tiktok publisher throws exception when no media', function () {
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(Exception::class, 'TikTok requires media (video or photos) to publish.');
});
test('tiktok publisher can publish video', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'PUBLISH_COMPLETE',
'publish_id' => 'pub_123',
],
], 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
expect($result['id'])->toBe('pub_123');
expect($result['url'])->toContain('tiktok.com/@tiktoker');
Http::assertSent(function ($request) {
return str_contains($request->url(), '/post/publish/video/init/');
});
});
Resume in-flight Instagram and TikTok publishes without duplicates (#281) * Improve asynchronous social publishing reliability * fix: resume asynchronous social publishes * fix: preserve publish checkpoints across retries * fix: harden resumable publish lifecycle * fix: clean retry resources on terminal failures * test: cover resumable social publishing edge cases * feat: add failed post retry command * chore: remove retry command ai rule * fix: require confirmation for post retries * chore: remove ai rules index * chore: remove ai social rule * refactor: clarify TikTok derivative path validation * refactor: simplify social publishing retries * refactor: further simplify social publishing retries * refactor: retry all failed post platforms * style: import throwable in social retries * refactor: decouple TikTok cleanup from image format * refactor: extract missing publish scopes * refactor: encapsulate missing scope failure * fix: resume failed publishes and treat Instagram rate limits as transient Keep TikTok/Instagram checkpoints on posts:retry so a manual retry does not start a duplicate remote post. Classify Meta BUC 400s on Instagram status polls as retryable via GraphError. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover resume paths and transient Instagram rate limits Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume posts:retry only for in-flight publish failures Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume posts:retry via ErrorCategory instead of string lists Co-authored-by: Cursor <cursoragent@cursor.com> * fix: handle Instagram PUBLISHED and EXPIRED container statuses Treat EXPIRED as a terminal server error so posts:retry starts over, and complete already-published containers without a second media_publish. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: recover published Instagram stories from /stories Stories are not on GET /{ig-user-id}/media. Resume a PUBLISHED story container from the stories edge so we do not bind a feed post id. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover Instagram EXPIRED retry and published recovery paths Co-authored-by: Cursor <cursoragent@cursor.com> * fix: stop guessing Instagram media ids from recent /media Co-authored-by: Cursor <cursoragent@cursor.com> * fix: checkpoint TikTok publish_id and keep in-flight photo derivatives Persist publish_id right after /init/ so a crash can resume without a second publish. Keep hosted photos while that id is resumable, including token expiry on status fetch; prune only after success or a confirmed remote failure. Co-authored-by: Cursor <cursoragent@cursor.com> * test: cover remaining TikTok in-flight derivative edge cases Guard the empty publish_id prune path, account guards without a checkpoint, and video status 401 after /init/. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor: map TikTok publish statuses with an official enum Use PublishStatus for status/fetch values from the Content Posting API. Keep only the documented cases, including FAILED as the terminal failure. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor: share in-flight publish checkpoint keys Read TikTok and Instagram resume state through one helper so publishers, posts:retry, and derivative cleanup agree on the same keys. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: retry Instagram media_publish after transient Graph failures A 500/code 2 after Meta already published left the job Failed as unknown. Treat that as still-processing so resume can confirm PUBLISHED instead of posting again. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: resume Instagram publish after dropped Graph connections A timeout or connection reset after Meta already published was marked unknown. Treat it as still-processing so resume can confirm PUBLISHED instead of posting again. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 18:34:53 +00:00
test('tiktok publisher does not report success before processing completes', function () {
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
]],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_processing']]),
$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_DOWNLOAD']]),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe(['tiktok_publish_id' => 'pub_processing'])
->and($exception->retryDelaySeconds)->toBe(30)
->and($exception->maxRetries)->toBe(120);
});
expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_processing');
Http::assertSentCount(2);
});
test('tiktok publisher checkpoints a video publish_id when status fetch reports an expired token', function () {
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
]],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_video_401']]),
$this->api.'/post/publish/status/fetch/' => Http::response([
'error' => [
'code' => 'access_token_invalid',
'message' => 'Access token is invalid',
],
], 401),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class);
expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_video_401');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/content/init/'));
});
test('tiktok publisher checkpoints a photo publish_id before polling status', function () {
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [[
'id' => 'test-media-image',
'path' => 'media/2026-01/image1.jpg',
'url' => 'https://example.com/media/2026-01/image1.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'image1.jpg',
'meta' => ['width' => 1080, 'height' => 1080],
]],
]);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response(['data' => ['publish_id' => 'pub_photo_processing']]),
$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_DOWNLOAD']]),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PlatformUnavailableException::class);
expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_processing');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/video/init/'));
});
test('tiktok publisher checkpoints photo derivatives with the publish_id before polling', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
]],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response(['data' => ['publish_id' => 'pub_photo_deriv']]),
$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_DOWNLOAD']]),
'*' => Http::response('fake-image-content', 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PlatformUnavailableException::class);
$context = $this->postPlatform->fresh()->error_context;
$paths = $context['tiktok_derivative_paths'] ?? null;
expect($context['tiktok_publish_id'] ?? null)->toBe('pub_photo_deriv')
->and($paths)->toBeArray()
->and($paths)->not->toBeEmpty();
foreach ($paths as $path) {
Storage::assertExists($path);
}
});
test('tiktok publisher keeps photo derivatives when status fetch reports an expired token', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
]],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response(['data' => ['publish_id' => 'pub_photo_401']]),
$this->api.'/post/publish/status/fetch/' => Http::sequence()
->push([
'error' => [
'code' => 'access_token_invalid',
'message' => 'Access token is invalid',
],
], 401)
->push([
'data' => [
'status' => 'PUBLISH_COMPLETE',
'publicaly_available_post_id' => ['video_123'],
],
]),
'*' => Http::response('fake-image-content', 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class);
$context = $this->postPlatform->fresh()->error_context;
$paths = $context['tiktok_derivative_paths'] ?? null;
expect($context['tiktok_publish_id'] ?? null)->toBe('pub_photo_401')
->and($paths)->toBeArray()
->and($paths)->not->toBeEmpty();
foreach ($paths as $path) {
Storage::assertExists($path);
}
$result = $this->publisher->publish($this->postPlatform->fresh());
expect($result['id'])->toBe('video_123');
foreach ($paths as $path) {
Storage::assertMissing($path);
}
expect(Http::recorded(fn ($request) => str_contains($request->url(), '/post/publish/content/init/')))
->toHaveCount(1);
});
test('tiktok publisher prunes photo derivatives when TikTok confirms the publish failed', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
]],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response(['data' => ['publish_id' => 'pub_photo_failed']]),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'FAILED',
'fail_reason' => 'photo_pull_failed',
],
]),
'*' => Http::response('fake-image-content', 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TikTokPublishException::class);
expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_failed')
->and(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher resumes an existing publish without creating a duplicate', function () {
$this->postPlatform->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'PUBLISH_COMPLETE',
'publicaly_available_post_id' => ['video_123'],
],
]),
]);
$result = $this->publisher->publish($this->postPlatform->fresh());
expect($result)->toBe([
'id' => 'video_123',
'url' => 'https://www.tiktok.com/@tiktoker/video/video_123',
]);
Http::assertSentCount(1);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('tiktok publisher retries a server-error status fetch without creating a duplicate', function () {
$this->postPlatform->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response(['error' => ['code' => 'internal_error']], 503),
]);
expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(503)
->and($exception->context['tiktok_publish_id'] ?? null)->toBe('pub_existing');
});
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('tiktok publisher retries a rate-limited status fetch without creating a duplicate', function () {
$this->postPlatform->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response(['error' => ['code' => 'rate_limit']], 429),
]);
expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(429)
->and($exception->context['tiktok_publish_id'] ?? null)->toBe('pub_existing');
});
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('tiktok publisher keeps photo derivatives while pending and prunes them on completion', function () {
Storage::fake();
$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($derivativePath, 'image');
$this->postPlatform->update([
'error_context' => [
'tiktok_publish_id' => 'pub_existing',
'tiktok_derivative_paths' => [$derivativePath],
],
]);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::sequence()
->push(['data' => ['status' => 'PROCESSING_DOWNLOAD']])
->push(['data' => ['status' => 'PUBLISH_COMPLETE', 'publicaly_available_post_id' => ['video_123']]]),
]);
expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
->toThrow(function (PlatformUnavailableException $exception) use ($derivativePath): void {
expect($exception->context['tiktok_derivative_paths'] ?? null)->toBe([$derivativePath]);
});
Storage::assertExists($derivativePath);
$result = $this->publisher->publish($this->postPlatform->fresh());
expect($result['id'])->toBe('video_123');
Storage::assertMissing($derivativePath);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('tiktok publisher can publish photos', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-image',
'path' => 'media/2026-01/image1.jpg',
'url' => 'https://example.com/media/2026-01/image1.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'image1.jpg',
'meta' => ['width' => 1080, 'height' => 1080],
],
],
]);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_photo_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'PUBLISH_COMPLETE',
'publish_id' => 'pub_photo_123',
],
], 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('pub_photo_123');
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
$body = json_decode($request->body(), true);
return data_get($body, 'post_info.description') === 'Check out this TikTok video!'
&& ! isset($body['post_info']['title']);
});
});
test('tiktok publisher throws exception on api error', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'error' => [
'code' => 'invalid_request',
'message' => 'Invalid request',
],
], 400),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(Exception::class);
});
test('tiktok publisher throws token expired exception on auth error', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'error' => [
'code' => 'access_token_invalid',
'message' => 'Access token is invalid',
],
], 401),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class);
});
test('tiktok publisher refreshes token when expired', function () {
$this->socialAccount->update(['token_expires_at' => now()->subHour()]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/oauth/token/' => Http::response([
'access_token' => 'new-access-token',
'refresh_token' => 'new-refresh-token',
'expires_in' => 86400,
], 200),
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'oauth/token');
});
$this->socialAccount->refresh();
expect($this->socialAccount->access_token)->toBe('new-access-token');
});
test('tiktok publisher throws exception when no refresh token available', function () {
$this->socialAccount->update([
'token_expires_at' => now()->subHour(),
'refresh_token' => null,
]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class, 'No refresh token available for TikTok account');
});
test('tiktok publisher throws TokenExpiredException when refresh_token is rejected', function () {
$this->socialAccount->update(['token_expires_at' => now()->subHour()]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/oauth/token/' => Http::response([
'error' => ['code' => 'invalid_grant', 'message' => 'Refresh token expired'],
], 400),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class, 'Refresh token expired');
});
test('tiktok publisher throws exception for unsupported media type', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-doc',
'path' => 'media/2026-01/doc.pdf',
'url' => 'https://example.com/media/2026-01/doc.pdf',
'mime_type' => 'application/pdf',
'original_filename' => 'doc.pdf',
],
],
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(Exception::class, 'TikTok only supports video or image content.');
});
test('tiktok publisher builds correct profile url when username present', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result['url'])->toBe('https://www.tiktok.com/@tiktoker');
});
test('tiktok publisher returns null url when username missing', function () {
$this->socialAccount->update(['username' => null]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result['url'])->toBeNull();
});
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
test('tiktok publisher publishes with user-selected privacy level even when creator info query fails', function () {
// User has explicitly selected SELF_ONLY in meta. creator_info failure must not block publishing.
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
// creator_info/query returns 500 — should not affect publishing since user picked privacy_level.
$this->api.'/post/publish/creator_info/query/' => Http::response([
'error' => ['code' => 'internal_error', 'message' => 'Internal server error'],
], 500),
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_fallback_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'PUBLISH_COMPLETE',
'publish_id' => 'pub_fallback_123',
],
], 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('pub_fallback_123');
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
// Assert SELF_ONLY (user's explicit pick) was used in the video init payload
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
return false;
}
$body = json_decode($request->body(), true);
return data_get($body, 'post_info.privacy_level') === 'SELF_ONLY';
});
});
test('tiktok publisher throws exception when publish fails', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => [
'status' => 'FAILED',
'fail_reason' => 'video_rejected',
],
], 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TikTokPublishException::class);
});
2026-04-02 20:57:06 +00:00
test('tiktok publisher sends meta settings in video publish request', function () {
$this->postPlatform->update([
'meta' => [
'privacy_level' => 'PUBLIC_TO_EVERYONE',
'allow_comments' => true,
'allow_duet' => false,
'allow_stitch' => true,
'is_aigc' => true,
'brand_content_toggle' => true,
'brand_organic_toggle' => false,
],
]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
2026-04-02 20:57:06 +00:00
]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => [
'privacy_level_options' => ['PUBLIC_TO_EVERYONE', 'SELF_ONLY'],
],
], 200),
$this->api.'/post/publish/video/init/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['publish_id' => 'pub_meta_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
return false;
}
$body = json_decode($request->body(), true);
$postInfo = data_get($body, 'post_info');
return $postInfo['privacy_level'] === 'PUBLIC_TO_EVERYONE'
&& $postInfo['disable_comment'] === false
&& $postInfo['disable_duet'] === true
&& $postInfo['disable_stitch'] === false
&& $postInfo['is_aigc'] === true
&& $postInfo['brand_content_toggle'] === true
&& ! isset($postInfo['brand_organic_toggle']);
});
});
test('tiktok publisher sends auto_add_music for photo posts', function () {
$this->postPlatform->update([
'meta' => [
'privacy_level' => 'SELF_ONLY',
'allow_comments' => true,
'auto_add_music' => true,
],
]);
$this->post->update([
'media' => [
[
'id' => 'test-media-photo',
'path' => 'media/2026-01/photo.jpg',
'url' => 'https://example.com/media/2026-01/photo.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'photo.jpg',
'meta' => ['width' => 1080, 'height' => 1080],
],
],
2026-04-02 20:57:06 +00:00
]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['privacy_level_options' => ['SELF_ONLY']],
], 200),
$this->api.'/post/publish/content/init/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['publish_id' => 'pub_music_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
$body = json_decode($request->body(), true);
$postInfo = data_get($body, 'post_info');
return $postInfo['auto_add_music'] === true
&& ! isset($postInfo['disable_duet'])
&& ! isset($postInfo['disable_stitch'])
&& ! isset($postInfo['is_aigc'])
&& ! isset($postInfo['title'])
&& isset($postInfo['description']);
2026-04-02 20:57:06 +00:00
});
});
test('tiktok publisher does not send auto_add_music for video posts', function () {
$this->postPlatform->update([
'meta' => [
'privacy_level' => 'SELF_ONLY',
'auto_add_music' => true,
],
]);
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
],
],
2026-04-02 20:57:06 +00:00
]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['privacy_level_options' => ['SELF_ONLY']],
], 200),
$this->api.'/post/publish/video/init/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['publish_id' => 'pub_vid_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
return false;
}
$body = json_decode($request->body(), true);
$postInfo = data_get($body, 'post_info');
return ! isset($postInfo['auto_add_music']);
});
});
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
test('tiktok publisher uses default settings when only privacy_level is set', function () {
// Only privacy_level is set (required); all other meta keys absent — exercise default toggles.
$this->postPlatform->update(['meta' => ['privacy_level' => 'PUBLIC_TO_EVERYONE']]);
2026-04-02 20:57:06 +00:00
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
2026-04-02 20:57:06 +00:00
]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => [
'privacy_level_options' => ['PUBLIC_TO_EVERYONE', 'FOLLOWER_OF_CREATOR', 'SELF_ONLY'],
],
], 200),
$this->api.'/post/publish/video/init/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['publish_id' => 'pub_default_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
2026-04-02 20:57:06 +00:00
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
return false;
}
$body = json_decode($request->body(), true);
$postInfo = data_get($body, 'post_info');
// privacy_level passes through; all interaction toggles default to OFF to match
// the UI checkbox state (TikTok UX guideline: none should be checked by default).
2026-04-02 20:57:06 +00:00
return $postInfo['privacy_level'] === 'PUBLIC_TO_EVERYONE'
&& $postInfo['disable_comment'] === true
2026-04-02 20:57:06 +00:00
&& $postInfo['disable_duet'] === true
&& $postInfo['disable_stitch'] === true
&& ! isset($postInfo['is_aigc'])
&& ! isset($postInfo['brand_content_toggle']);
});
});
test('tiktok publisher sends video caption in title field, never description', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
'content' => 'My video caption',
]);
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
'data' => [
'privacy_level_options' => ['SELF_ONLY'],
],
], 200),
$this->api.'/post/publish/video/init/' => Http::response([
'data' => ['publish_id' => 'pub_video_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE', 'publish_id' => 'pub_video_123'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
return false;
}
$body = json_decode($request->body(), true);
return data_get($body, 'post_info.title') === 'My video caption'
&& ! isset($body['post_info']['description']);
});
});
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
test('tiktok publisher throws when meta.privacy_level is missing and user did not pick', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
// Explicitly clear privacy_level from meta (simulate UI never set it).
$this->postPlatform->update(['meta' => []]);
Http::fake([
// creator_info returns a healthy response — fallback would have silently picked PUBLIC_TO_EVERYONE.
$this->api.'/post/publish/creator_info/query/' => Http::response([
feat(tiktok): photo carousel support + UX Content Sharing API compliance ## Photo carousel support - Adds `ContentType::TikTokPhoto` enum case (max 35 photos, 1:1 aspect, supportsImage true, supportsVideo false) and JS mirror in content-type.ts. - Variant pill picker (Video / Photo carousel) at the top of TikTokSettings, mirroring the Instagram pattern. Wired through ScheduleTab to the parent editor's existing update:platformContentType emit. - i18n keys for variant_label / variant.video / variant.photo in en/pt-BR/es. - Publisher: split buildPostInfo into buildVideoPostInfo (uses `title`, TikTok cap 2200 chars) and buildPhotoPostInfo (uses `description`, cap 4000 chars; omits Duet/Stitch/AIGC since they don't apply). Removed the no-longer-needed queryCreatorInfo() call from publishVideo/publishPhotos — its only previous consumer (silent privacy_level fallback) is gone. ## UX Content Sharing API compliance Per TikTok review feedback citing https://developers.tiktok.com/doc/content-sharing-guidelines#required_ux_implementation_in_your_app Point 1 — already satisfied (creator_info fetch + nickname display). Point 2/4 — Music Usage Confirmation declaration is now always visible in TikTokSettings; text changes between "Music Usage Confirmation" and "Branded Content Policy and Music Usage Confirmation" based on toggle state. Previously the entire `<p>` block was conditional on a brand toggle being selected, hiding the baseline declaration. Point 2b — privacy_level may not have a default. UI was already correct; backend hardened: UpdatePostRequest now requires meta.privacy_level for tiktok platforms when status is publishing/scheduled (via withValidator); TikTokPublisher::resolveRequiredPrivacyLevel throws TikTokPublishException (ContentPolicy category) when missing instead of silently falling back to the creator's preferred level. Point 2c — interaction settings now condition on content type: - Photo posts hide Duet/Stitch (they don't apply per TikTok docs). - Photo posts hide AIGC (also video-only). - Video posts hide Auto Add Music (photos-only feature). - Max-duration warning hidden when not a video post. Source of truth is the user-selected contentType prop, not inferred from media — ensures the UI reacts immediately to the variant pill. Point 3a — publish button stays disabled when Disclose toggle is on without a sub-selection (already the case via tiktokComplianceValid). The disabled tooltip now uses the verbatim TikTok-required text "You need to indicate if your content promotes yourself, a third party, or both." instead of the generic "Some platform settings are incomplete..." when the only blocker is TikTok disclosure incompleteness. Point 3b — SELF_ONLY (Only me) privacy option is no longer filtered out when Branded Content is checked. It is rendered disabled with a hover tooltip "Branded content visibility cannot be set to private." plus a persistent amber warning paragraph below the dropdown. When the user toggles Branded Content while privacy is SELF_ONLY, the privacy clears and a vue-sonner warning toast surfaces the change. ## Cross-cutting - New `resources/js/enums/platform.ts` mirrors the PHP Platform enum, used in Edit.vue (tiktokComplianceValid + tiktokDisclosureIncomplete) and ScheduleTab.vue (all selected*Platforms computeds) to replace string literal comparisons against `'tiktok'` / `'facebook'` / etc. - PostPlatformFactory tiktok() state defaults meta.privacy_level to SELF_ONLY so existing test fixtures keep passing under the new publisher/FormRequest requirements. ## Tests - New tests/Unit/Enums/PostPlatform/TikTokPhotoContentTypeTest.php covering the new enum case (4 tests). - TikTokPublisherTest: added "video uses title not description" and "throws when meta.privacy_level missing" regression tests; renamed two existing tests that depended on the removed silent fallback. - New tests/Feature/UpdatePostRequestTest.php with 3 tests covering the FormRequest's privacy_level enforcement (publish-rejected, publish-passes, draft-allowed). Full Pest suite: 1490 passed, 2 skipped (pre-existing).
2026-05-09 15:47:49 +00:00
'data' => [
'creator_nickname' => 'test',
'creator_username' => 'test',
'privacy_level_options' => ['PUBLIC_TO_EVERYONE', 'SELF_ONLY'],
'comment_disabled' => false,
'duet_disabled' => false,
'stitch_disabled' => false,
'max_video_post_duration_sec' => 300,
],
], 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TikTokPublishException::class);
});
test('tiktok publisher resizes an oversized photo and pulls a hosted compliant copy', function () {
Storage::fake();
// TikTok rejects images wider than 1080px; this one is 1254px wide.
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'test-media-oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_resize_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
'*' => Http::response('fake-image-content', 200),
]);
$this->publisher->publish($this->postPlatform);
// TikTok must be handed the hosted derivative, never the oversized original.
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
$photoUrl = data_get(json_decode($request->body(), true), 'source_info.photo_images.0');
return str_contains($photoUrl, 'social-tiktok-photos/')
&& ! str_contains($photoUrl, 'example.com');
});
// The derivative is pruned once TikTok has pulled it.
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher passes a compliant photo through without hosting a copy', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'test-media-compliant',
'path' => 'media/2026-01/ok.jpg',
'url' => 'https://example.com/media/2026-01/ok.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'ok.jpg',
'meta' => ['width' => 1080, 'height' => 1920],
],
],
]);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_passthrough_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
// The original URL is published unchanged and nothing is downloaded or hosted.
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
return data_get(json_decode($request->body(), true), 'source_info.photo_images.0')
=== 'https://example.com/media/2026-01/ok.jpg';
});
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'example.com'));
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher resizes a photo when its dimensions are unknown', function () {
Storage::fake();
// No width/height metadata: fall back to the safe path and host a compliant copy.
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'test-media-unknown',
'path' => 'media/2026-01/unknown.jpg',
'url' => 'https://example.com/media/2026-01/unknown.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'unknown.jpg',
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_unknown_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
'*' => Http::response('fake-image-content', 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
return str_contains(
(string) data_get(json_decode($request->body(), true), 'source_info.photo_images.0'),
'social-tiktok-photos/'
);
});
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher fails clearly when an oversized photo cannot be downloaded for resizing', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'test-media-oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
],
],
]);
// optimizeImage is intentionally not stubbed: it must never be reached when the
// download fails, and the strict mock would throw if it were called.
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
'*' => Http::response('not found', 500),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TikTokPublishException::class, 'Failed to download image for TikTok resizing');
// Nothing should be left hosted when resizing never completes.
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher resizes only the oversized photos in a mixed carousel', function () {
Storage::fake();
// TikTok carousels can carry many images; here one is oversized, one is compliant.
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
],
[
'id' => 'compliant',
'path' => 'media/2026-01/small.jpg',
'url' => 'https://example.com/media/2026-01/small.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'small.jpg',
'meta' => ['width' => 1080, 'height' => 1080],
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
// optimizeImage must run exactly once — only for the oversized image.
$mockOptimizer->shouldReceive('optimizeImage')->once()->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_mixed_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
'*' => Http::response('fake-image-content', 200),
]);
$this->publisher->publish($this->postPlatform);
// Order is preserved: oversized -> hosted derivative, compliant -> original URL untouched.
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
return false;
}
$images = data_get(json_decode($request->body(), true), 'source_info.photo_images');
return is_array($images)
&& count($images) === 2
&& str_contains($images[0], 'social-tiktok-photos/')
&& ! str_contains($images[0], 'example.com')
&& $images[1] === 'https://example.com/media/2026-01/small.jpg';
});
// The compliant image is never downloaded; only the oversized one is fetched for resizing.
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'small.jpg'));
// The single derivative is pruned after publish.
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher prunes the hosted derivative even when publishing fails', function () {
Storage::fake();
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
// The derivative is hosted first, then TikTok rejects the publish: the finally
// must still remove it so a failed post never orphans a file on disk.
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'error' => ['code' => 'internal_error', 'message' => 'boom'],
], 500),
'*' => Http::response('fake-image-content', 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TikTokPublishException::class);
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher still reports success when derivative cleanup throws on the storage disk', function () {
// The production default disk (r2) is configured to throw on a failed delete.
// Cleanup must never turn an already-published post into a reported failure.
$this->postPlatform->update(['meta' => ['privacy_level' => 'SELF_ONLY']]);
$this->post->update([
'media' => [
[
'id' => 'oversized',
'path' => 'media/2026-01/big.jpg',
'url' => 'https://example.com/media/2026-01/big.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'big.jpg',
'meta' => ['width' => 1254, 'height' => 1254],
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('maxWidthForPlatform')->with(Platform::TikTok)->andReturn(1080);
$mockOptimizer->shouldReceive('optimizeImage')->with(Mockery::type('string'), Platform::TikTok)->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'tt_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Storage::shouldReceive('put')->andReturnTrue();
Storage::shouldReceive('url')->andReturn('https://cdn.example.com/social-tiktok-photos/x.jpg');
Storage::shouldReceive('delete')->andThrow(new RuntimeException('r2 delete failed'));
Http::fake([
$this->api.'/post/publish/content/init/' => Http::response([
'data' => ['publish_id' => 'pub_cleanup_throws_123'],
], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE'],
], 200),
'*' => Http::response('fake-image-content', 200),
]);
$result = $this->publisher->publish($this->postPlatform);
expect($result['id'])->toBe('pub_cleanup_throws_123');
});
Defuse links in X posts to avoid the link-post fee (#308) 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.
2026-08-29 18:31:05 +00:00
test('tiktok publisher keeps links intact', function () {
config()->set('trypost.platforms.x.defuse_links', true);
$this->post->update([
'content' => 'New post: https://acme.com/blog',
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
'url' => 'https://example.com/media/2026-01/test-video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
]],
]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_123']], 200),
$this->api.'/post/publish/status/fetch/' => Http::response([
'data' => ['status' => 'PUBLISH_COMPLETE', 'publish_id' => 'pub_123'],
], 200),
]);
$this->publisher->publish($this->postPlatform);
Http::assertSent(fn ($request) => str_contains($request->url(), '/video/init/')
&& data_get($request->data(), 'post_info.title') === 'New post: https://acme.com/blog');
});