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

92 lines
2.7 KiB
PHP
Raw Normal View History

2025-06-29 21:20:45 +02:00
<?php
namespace App\Modules\Lemmy\Services;
use App\Modules\Lemmy\LemmyRequest;
use Exception;
class LemmyApiService
{
private string $instance;
public function __construct(string $instance)
{
$this->instance = $instance;
}
public function login(string $username, string $password): ?string
{
try {
$request = new LemmyRequest($this->instance);
$response = $request->post('user/login', [
'username_or_email' => $username,
'password' => $password,
]);
if (!$response->successful()) {
logger()->error('Lemmy login failed', [
'status' => $response->status(),
'body' => $response->body()
]);
return null;
}
$data = $response->json();
return $data['jwt'] ?? null;
} catch (Exception $e) {
logger()->error('Lemmy login exception', ['error' => $e->getMessage()]);
return null;
}
}
public function getCommunityId(string $communityName): int
{
try {
$request = new LemmyRequest($this->instance);
$response = $request->get('community', ['name' => $communityName]);
if (!$response->successful()) {
throw new Exception('Failed to fetch community: ' . $response->status());
}
$data = $response->json();
return $data['community_view']['community']['id'] ?? throw new Exception('Community not found');
} catch (Exception $e) {
logger()->error('Community lookup failed', ['error' => $e->getMessage()]);
throw $e;
}
}
2025-06-30 18:18:30 +02:00
public function createPost(string $token, string $title, string $body, int $communityId, ?string $url = null, ?string $thumbnail = null): array
2025-06-29 21:20:45 +02:00
{
try {
$request = new LemmyRequest($this->instance, $token);
2025-06-30 18:18:30 +02:00
$postData = [
2025-06-29 21:20:45 +02:00
'name' => $title,
'body' => $body,
'community_id' => $communityId,
2025-06-30 18:18:30 +02:00
];
if ($url) {
$postData['url'] = $url;
}
if ($thumbnail) {
$postData['custom_thumbnail'] = $thumbnail;
}
$response = $request->post('post', $postData);
2025-06-29 21:20:45 +02:00
if (!$response->successful()) {
throw new Exception('Failed to create post: ' . $response->status() . ' - ' . $response->body());
}
return $response->json();
} catch (Exception $e) {
logger()->error('Post creation failed', ['error' => $e->getMessage()]);
throw $e;
}
}
2025-06-30 18:18:30 +02:00
}