fedi-feed-router/app/Jobs/SyncChannelPostsJob.php

76 lines
2.2 KiB
PHP

<?php
namespace App\Jobs;
use App\Enums\PlatformEnum;
use App\Exceptions\PlatformAuthException;
use App\Modules\Lemmy\Services\LemmyApiService;
use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
class SyncChannelPostsJob implements ShouldQueue
{
use Queueable;
public function __construct(
private readonly PlatformEnum $platform,
private readonly string $channelId,
private readonly string $channelName
) {
$this->onQueue('lemmy-posts');
}
public function handle(): void
{
if ($this->platform === PlatformEnum::LEMMY) {
$this->syncLemmyChannelPosts();
}
}
private function syncLemmyChannelPosts(): void
{
try {
$api = new LemmyApiService(config('lemmy.instance'));
$token = $this->getAuthToken($api);
$api->syncChannelPosts($token, (int) $this->channelId, $this->channelName);
logger()->info('Channel posts synced successfully', [
'platform' => $this->platform->value,
'channel_id' => $this->channelId,
'channel_name' => $this->channelName
]);
} catch (Exception $e) {
logger()->error('Failed to sync channel posts', [
'platform' => $this->platform->value,
'channel_id' => $this->channelId,
'error' => $e->getMessage()
]);
throw $e;
}
}
private function getAuthToken(LemmyApiService $api): string
{
return Cache::remember('lemmy_jwt_token', 3600, function () use ($api) {
$username = config('lemmy.username');
$password = config('lemmy.password');
if (!$username || !$password) {
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials');
}
$token = $api->login($username, $password);
if (!$token) {
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed');
}
return $token;
});
}
}