Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use He4rt\IntegrationDiscord\ETL\Console\ImportDiscordProfilesCommand;
use He4rt\IntegrationDiscord\ETL\Console\MergeDuplicateDiscordProfilesCommand;
use He4rt\IntegrationDiscord\Models\DiscordEventLog;
use He4rt\IntegrationDiscord\Sync\Console\PurgeUnusedInvitesCommand;
use He4rt\IntegrationDiscord\Sync\Console\SyncDiscordGuildCommand;
use He4rt\IntegrationDiscord\Sync\Observers\DiscordEventLogObserver;
use He4rt\IntegrationDiscord\Transport\DiscordConnector;
Expand Down Expand Up @@ -41,6 +42,7 @@ public function boot(): void
MergeDuplicateDiscordProfilesCommand::class,
SyncDiscordGuildCommand::class,
BackfillVoiceLogsCommand::class,
PurgeUnusedInvitesCommand::class,
]);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

declare(strict_types=1);

namespace He4rt\IntegrationDiscord\Sync\Actions;

use He4rt\IntegrationDiscord\Transport\DiscordConnector;
use He4rt\IntegrationDiscord\Transport\Requests\Invites\DeleteInvite;
use He4rt\IntegrationDiscord\Transport\Requests\Invites\ListGuildInvites;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use RuntimeException;
use Throwable;

final readonly class PurgeUnusedInvitesAction
{
public function __construct(
private DiscordConnector $connector,
) {}

/**
* @return array{total: int, matched: int, deleted: int, failed: int, invites: list<array{code: string, channel: string, inviter: string, created_at: string}>}
*/
public function execute(string $guildId, bool $dryRun = false, bool $includeExpiring = false): array
{
$response = $this->connector->send(new ListGuildInvites($guildId));

if ($response->failed()) {
throw new RuntimeException(sprintf('Failed to list guild invites: HTTP %d', $response->status()));
}

/** @var list<array<string, mixed>> $allInvites */
$allInvites = $response->json();
Comment thread
coderabbitai[bot] marked this conversation as resolved.

$unused = array_filter(
$allInvites,
static fn (array $invite): bool => ($invite['uses'] ?? -1) === 0
&& ($includeExpiring || ($invite['max_age'] ?? -1) === 0),
);

$matches = array_values(array_map(
static fn (array $invite): array => [
'code' => $invite['code'],
'channel' => $invite['channel']['name'] ?? 'unknown',
'inviter' => $invite['inviter']['username'] ?? 'unknown',
'created_at' => isset($invite['created_at'])
? Date::parse($invite['created_at'])->timezone(config('app.display_timezone'))->format('d/m/Y H:i')
: '',
],
$unused,
));

if ($dryRun) {
return [
'total' => count($allInvites),
'matched' => count($unused),
'deleted' => 0,
'failed' => 0,
'invites' => $matches,
];
}

$deleted = 0;
$failed = 0;

foreach ($unused as $index => $invite) {
if ($index > 0) {
Sleep::usleep(random_int(200_000, 500_000));
}

try {
$response = $this->connector->send(new DeleteInvite($invite['code']));

if ($response->failed()) {
throw new RuntimeException(sprintf('HTTP %d: %s', $response->status(), $response->body()));
}

$deleted++;
} catch (Throwable $e) {
$failed++;
Log::warning('Failed to delete Discord invite', [
'code' => $invite['code'],
'error' => $e->getMessage(),
]);
}
}

return [
'total' => count($allInvites),
'matched' => count($unused),
'deleted' => $deleted,
'failed' => $failed,
'invites' => $matches,
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

namespace He4rt\IntegrationDiscord\Sync\Console;

use He4rt\IntegrationDiscord\Sync\Actions\PurgeUnusedInvitesAction;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Description('Purge unused infinite Discord guild invites (max_age=0, uses=0)')]
#[Signature('discord:purge-invites {guild_id?} {--dry-run : List invites without deleting} {--include-expiring : Also purge unused invites that have an expiration time}')]
final class PurgeUnusedInvitesCommand extends Command
{
public function handle(PurgeUnusedInvitesAction $action): int
{
$guildId = $this->argument('guild_id') ?? config('he4rt.discord.guild_id');

if ($guildId === null) {
$this->error('No guild ID provided and no default configured.');

return self::FAILURE;
}

$dryRun = (bool) $this->option('dry-run');
$includeExpiring = (bool) $this->option('include-expiring');

$scope = $includeExpiring ? 'unused' : 'unused infinite';

$this->info(sprintf(
'%s %s invites for guild %s...',
$dryRun ? 'Scanning' : 'Purging',
$scope,
$guildId,
));

$result = $action->execute((string) $guildId, $dryRun, $includeExpiring);

if ($result['matched'] === 0) {
$this->info(sprintf('No %s invites found. Nothing to do.', $scope));

return self::SUCCESS;
}

$this->table(
['Code', 'Inviter', 'Channel', 'Created At'],
array_map(
static fn (array $invite): array => [
$invite['code'],
$invite['inviter'],
$invite['channel'],
$invite['created_at'],
],
$result['invites'],
),
);

$this->newLine();
$this->info(sprintf(
'Found %d %s invite(s) out of %d total.',
$result['matched'],
$scope,
$result['total'],
));

if ($dryRun) {
$this->warn('DRY RUN -- no invites were deleted.');

return self::SUCCESS;
}

$this->info(sprintf('Deleted %d invite(s).', $result['deleted']));

if ($result['failed'] > 0) {
$this->warn(sprintf('%d invite(s) failed to delete. Check logs for details.', $result['failed']));

return self::FAILURE;
}

return self::SUCCESS;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace He4rt\IntegrationDiscord\Transport\Requests\Invites;

use Saloon\Enums\Method;
use Saloon\Http\Request;

final class DeleteInvite extends Request
{
protected Method $method = Method::DELETE;

public function __construct(
private readonly string $inviteCode,
) {}

public function resolveEndpoint(): string
{
return sprintf('/invites/%s', $this->inviteCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace He4rt\IntegrationDiscord\Transport\Requests\Invites;

use Saloon\Enums\Method;
use Saloon\Http\Request;

final class ListGuildInvites extends Request
{
protected Method $method = Method::GET;

public function __construct(
private readonly string $guildId,
) {}

public function resolveEndpoint(): string
{
return sprintf('/guilds/%s/invites', $this->guildId);
}
}
Loading