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

86 lines
2.5 KiB
PHP
Raw Normal View History

2025-06-29 21:20:45 +02:00
<?php
namespace App\Modules\Lemmy\Services;
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')
);
}
public function publish(Article $article, array $extractedData): ArticlePublication
{
$token = $this->getAuthToken();
if (!$token) {
throw new Exception('Failed to authenticate with Lemmy');
}
$communityId = $this->getCommunityId();
$postData = $this->api->createPost(
$token,
$extractedData['title'] ?? 'Untitled',
$extractedData['description'] ?? '',
$communityId
);
return $this->createPublicationRecord($article, $postData, $communityId);
}
private function getAuthToken(): ?string
{
return Cache::remember('lemmy_jwt_token', 3600, function () {
$username = config('lemmy.username');
$password = config('lemmy.password');
if (!$username || !$password) {
logger()->error('Missing Lemmy credentials');
return null;
}
return $this->api->login($username, $password);
});
}
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,
]);
}
}