From 029981f838af7e03bf367f8d3b2f5b59949c04fb Mon Sep 17 00:00:00 2001 From: myrmidex Date: Sat, 15 Aug 2026 02:04:43 +0200 Subject: [PATCH] 150 - Authenticate once per instance in the community id migration --- ...eric_community_id_on_platform_channels.php | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/database/migrations/2024_01_01_000015_store_numeric_community_id_on_platform_channels.php b/database/migrations/2024_01_01_000015_store_numeric_community_id_on_platform_channels.php index 4f907e4f..901c3211 100644 --- a/database/migrations/2024_01_01_000015_store_numeric_community_id_on_platform_channels.php +++ b/database/migrations/2024_01_01_000015_store_numeric_community_id_on_platform_channels.php @@ -67,6 +67,9 @@ public function down(): void }); } + /** @var array */ + private array $sessions = []; + private function resolve(object $channel): int { if (is_numeric($channel->channel_id)) { @@ -79,21 +82,38 @@ private function resolve(object $channel): int throw new RuntimeException("Channel {$channel->id} has no platform instance; cannot resolve its community id."); } - $account = PlatformAccount::where('instance_url', $instance->url) + $session = $this->session($instance->url, $channel->channel_id); + + return $session['api']->getCommunityId($channel->channel_id, $session['token']); + } + + /** + * Lemmy rate-limits logins, so authenticate once per instance rather than + * once per channel. + * + * @return array{api: LemmyApiService, token: string} + */ + private function session(string $url, string $community): array + { + if (isset($this->sessions[$url])) { + return $this->sessions[$url]; + } + + $account = PlatformAccount::where('instance_url', $url) ->where('is_active', true) ->first(); if (! $account) { - throw new RuntimeException("No active account for {$instance->url}; cannot resolve community '{$channel->channel_id}'."); + throw new RuntimeException("No active account for {$url}; cannot resolve community '{$community}'."); } - $api = new LemmyApiService($instance->url); + $api = new LemmyApiService($url); $token = $api->login($account->username, $account->password); if (! $token) { - throw new RuntimeException("Could not authenticate against {$instance->url} to resolve community '{$channel->channel_id}'."); + throw new RuntimeException("Could not authenticate against {$url} to resolve community '{$community}'."); } - return $api->getCommunityId($channel->channel_id, $token); + return $this->sessions[$url] = ['api' => $api, 'token' => $token]; } };