fedi-feed-router/app/Modules/Lemmy/Services/LemmyPublisher.php

98 lines
2.9 KiB
PHP

<?php
namespace App\Modules\Lemmy\Services;
use App\Enums\PlatformEnum;
use App\Exceptions\PlatformAuthException;
use App\Exceptions\PublishException;
use App\Models\Article;
use App\Models\ArticlePublication;
use Exception;
use Illuminate\Support\Facades\Cache;
class LemmyPublisher
{
private LemmyApiService $api;
private string $username;
private string $community;
public function __construct(string $instance, string $username, string $community)
{
$this->api = new LemmyApiService($instance);
$this->username = $username;
$this->community = $community;
}
public static function fromConfig(): self
{
return new self(
config('lemmy.instance'),
config('lemmy.username'),
config('lemmy.community')
);
}
/**
* @throws PublishException
*/
public function publish(Article $article, array $extractedData): ArticlePublication
{
try {
$token = $this->getAuthToken();
$communityId = $this->getCommunityId();
$postData = $this->api->createPost(
$token,
$extractedData['title'] ?? 'Untitled',
$extractedData['description'] ?? '',
$communityId,
$article->url,
$extractedData['thumbnail'] ?? null
);
return $this->createPublicationRecord($article, $postData, $communityId);
} catch (Exception $e) {
throw new PublishException($article, PlatformEnum::LEMMY, $e);
}
}
private function getAuthToken(): string
{
return Cache::remember('lemmy_jwt_token', 3600, function () {
$username = config('lemmy.username');
$password = config('lemmy.password');
if (!$username || !$password) {
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials');
}
$token = $this->api->login($username, $password);
if (!$token) {
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed');
}
return $token;
});
}
private function getCommunityId(): int
{
return Cache::remember("lemmy_community_id_{$this->community}", 3600, function () {
return $this->api->getCommunityId($this->community);
});
}
private function createPublicationRecord(Article $article, array $postData, int $communityId): ArticlePublication
{
return ArticlePublication::create([
'article_id' => $article->id,
'post_id' => $postData['post_view']['post']['id'],
'community_id' => $communityId,
'published_by' => $this->username,
'published_at' => now(),
'platform' => 'lemmy',
'publication_data' => $postData,
]);
}
}