150 - Authenticate once per instance in the community id migration #151
1 changed files with 25 additions and 5 deletions
|
|
@ -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
|
||||
{
|
||||
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];
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue