Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions app/Services/Post/PostMetricsFetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use App\Services\Social\YouTubeAnalytics;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
* Fetches per-platform post metrics. Used by the web controller, the REST
Expand Down Expand Up @@ -62,7 +63,8 @@ public function forPlatform(PostPlatform $postPlatform): array
return ['unsupported' => true, 'reason' => 'not_published'];
}

return Cache::remember("post_metrics:{$postPlatform->id}", 300, fn () => match ($postPlatform->platform) {
try {
return Cache::remember("post_metrics:{$postPlatform->id}", 300, fn () => match ($postPlatform->platform) {
Platform::X => app(XAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Bluesky => app(BlueskyAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Mastodon => app(MastodonAnalytics::class)->fetchPostMetrics($postPlatform),
Expand All @@ -75,6 +77,18 @@ public function forPlatform(PostPlatform $postPlatform): array
Platform::YouTube => app(YouTubeAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Pinterest => app(PinterestAnalytics::class)->fetchPostMetrics($postPlatform),
default => ['unsupported' => true, 'reason' => 'platform_not_supported'],
});
});
} catch (\Throwable $e) {
// Один упавший провайдер (протухший токен, квота, сетевой сбой) не
// должен ронять метрики всего поста — остальные платформы отдаются.
Log::warning('Post metrics fetch failed for platform', [
'post_platform_id' => $postPlatform->id,
'platform' => $postPlatform->platform->value,
'exception' => $e::class,
'error' => $e->getMessage(),
]);

return ['unsupported' => true, 'reason' => 'error'];
}
}
}
5 changes: 4 additions & 1 deletion app/Services/Social/ConnectionVerifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,11 @@ private function refreshBlueskyToken(SocialAccount $account): void
$client = TokenRefreshClient::for(Platform::Bluesky);

try {
// refreshSession must be POSTed with NO body: `post()` without data
// still sends an empty JSON body, and bsky.social now rejects it
// with "A request body was provided when none was expected".
$response = $client->send(fn () => $this->refreshHttp()->withToken($account->refresh_token)
->post("{$service}/xrpc/".BlueskyLexicon::REFRESH_SESSION));
->send('POST', "{$service}/xrpc/".BlueskyLexicon::REFRESH_SESSION));

$data = $response->json();
$account->update([
Expand Down
43 changes: 43 additions & 0 deletions tests/Feature/Services/Post/PostMetricsFetcherTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Post\PostMetricsFetcher;
use App\Services\Social\XAnalytics;

beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'content' => 'x',
]);
});

test('a provider exception degrades to an unsupported entry instead of failing the aggregate', function () {
$account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
$row = PostPlatform::factory()->create([
'post_id' => $this->post->id,
'social_account_id' => $account->id,
'platform' => Platform::X,
'content_type' => ContentType::XPost,
'status' => \App\Enums\PostPlatform\Status::Published,
'platform_post_id' => '123',
]);

$this->mock(XAnalytics::class)
->shouldReceive('fetchPostMetrics')
->andThrow(new RuntimeException('token expired mid-flight'));

$metrics = app(PostMetricsFetcher::class)->forPlatform($row->fresh());

expect($metrics)->toBe(['unsupported' => true, 'reason' => 'error']);
});
38 changes: 38 additions & 0 deletions tests/Feature/Services/Social/BlueskyRefreshSessionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\ConnectionVerifier;
use Illuminate\Support\Facades\Http;

test('bluesky refresh posts refreshSession with no request body', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$account = SocialAccount::factory()->bluesky()->create([
'workspace_id' => $workspace->id,
'refresh_token' => 'refresh-jwt',
]);

$service = config('trypost.platforms.bluesky.default_service');

Http::fake([
"{$service}/xrpc/com.atproto.server.refreshSession" => Http::response([
'accessJwt' => 'new-access',
'refreshJwt' => 'new-refresh',
], 200),
]);

app(ConnectionVerifier::class)->refreshToken($account);

// bsky.social rejects refreshSession when any body is present — even the
// empty JSON object/array a data-less post() would send.
Http::assertSent(function ($request) {
return str_contains($request->url(), 'refreshSession')
&& $request->body() === '';
});

expect($account->fresh()->access_token)->toBe('new-access');
});