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, ]); } }