70 lines
1.9 KiB
PHP
70 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Article;
|
|
|
|
use App\Models\Article;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Exception;
|
|
|
|
class LemmyService
|
|
{
|
|
public static function publish(Article $article): bool
|
|
{
|
|
$jwt = self::getJwtToken();
|
|
dd(['jwt' => $jwt]);
|
|
|
|
// $instance = config('lemmy.instance');
|
|
// $community = config('lemmy.community');
|
|
//
|
|
// $response = file_get_contents("https://$instance/api/v3/community?name=$community");
|
|
// $data = json_decode($response, true);
|
|
//
|
|
// dd($data);
|
|
//// return $data['community_view']['community']['id'] ?? null;
|
|
//
|
|
// logger('publishing ' . $article . ' - ' . $article->url);
|
|
|
|
return true;
|
|
}
|
|
|
|
private static function getJwtToken(): ?string
|
|
{
|
|
return Cache::remember('lemmy_jwt_token', 3600, function () {
|
|
return self::login();
|
|
});
|
|
}
|
|
|
|
private static function login(): ?string
|
|
{
|
|
$username = config('lemmy.username');
|
|
$password = config('lemmy.password');
|
|
$instance = config('lemmy.instance');
|
|
|
|
if (!$username || !$password || !$instance) {
|
|
logger()->error('Missing Lemmy configuration');
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
$response = Http::post("https://$instance/api/v3/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;
|
|
}
|
|
}
|
|
}
|