150 - Authenticate once per instance in the community id migration
Some checks failed
CI / ci (pull_request) Failing after 11m41s

This commit is contained in:
myrmidex 2026-08-15 02:04:43 +02:00
parent de42bdca38
commit 029981f838

View file

@ -67,6 +67,9 @@ public function down(): void
}); });
} }
/** @var array<string, array{api: LemmyApiService, token: string}> */
private array $sessions = [];
private function resolve(object $channel): int private function resolve(object $channel): int
{ {
if (is_numeric($channel->channel_id)) { 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."); 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) ->where('is_active', true)
->first(); ->first();
if (! $account) { 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); $token = $api->login($account->username, $account->password);
if (! $token) { 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];
} }
}; };