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 { $cachedToken = Cache::get('lemmy_jwt_token'); if ($cachedToken) { return $cachedToken; } $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'); } Cache::put('lemmy_jwt_token', $token, 3600); return $token; } private function getCommunityId(): int { $cacheKey = "lemmy_community_id_{$this->community}"; $cachedId = Cache::get($cacheKey); if ($cachedId) { return $cachedId; } $communityId = $this->api->getCommunityId($this->community); Cache::put($cacheKey, $communityId, 3600); return $communityId; } 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, ]); } }