Skip to content
Open
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
7 changes: 7 additions & 0 deletions app/Actions/CreateGuild.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace App\Actions;

use App\Exceptions\GuildModeratorLimitReached;
use App\Exceptions\GuildModeratorRemoved;
use App\Http\Requests\CreateGuildRequest;
use App\Models\Guild;
use App\Models\User;
use Illuminate\Http\UploadedFile;
Expand All @@ -22,6 +24,11 @@ public function handle(User $user, string $handle, string $name, string $descrip
return DB::transaction(function () use ($user, $handle, $name, $description, $emoji, $icon): Guild {
User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();

// Counted again under the lock, since a handover may have given the user another guild after validation.
if (Guild::query()->where('user_id', $user->id)->count() >= CreateGuildRequest::MAX_PER_USER) {
throw new GuildModeratorLimitReached;
}

if (DB::table('guild_moderator_removals')->where('github_id', $user->github_id)->where('handle', mb_strtolower($handle))->exists()) {
throw new GuildModeratorRemoved;
}
Expand Down
40 changes: 36 additions & 4 deletions app/Actions/UpdateGuild.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

use App\Enums\UserUpdate;
use App\Events\UsersUpdated;
use App\Exceptions\GuildModeratorLimitReached;
use App\Exceptions\GuildModeratorNotMember;
use App\Exceptions\GuildModeratorRemoved;
use App\Http\Requests\CreateGuildRequest;
use App\Models\Guild;
use App\Models\User;
use Illuminate\Http\UploadedFile;
Expand All @@ -19,24 +22,53 @@ public function __construct(private CreateImageFiles $images, private DeleteStor
//
}

public function handle(Guild $guild, User $user, string $description, string $emoji, ?UploadedFile $icon, bool $removeIcon): void
/**
* A new moderator must still be a member with room for another guild when the guild is saved. Their row is locked before
* the guild, like joining and creating guilds do, so they cannot leave or take on more guilds halfway through the handover.
*/
public function handle(Guild $guild, User $user, string $description, string $emoji, ?UploadedFile $icon, bool $removeIcon, ?User $moderator = null): void
{
DB::transaction(function () use ($guild, $user, $description, $emoji, $icon, $removeIcon): void {
DB::transaction(function () use ($guild, $user, $description, $emoji, $icon, $removeIcon, $moderator): void {
$handover = $moderator instanceof User && $moderator->id !== $user->id;

if ($handover) {
User::query()->whereKey($moderator->id)->lockForUpdate()->firstOrFail();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if (Guild::query()->where('user_id', $moderator->id)->count() >= CreateGuildRequest::MAX_PER_USER) {
throw new GuildModeratorLimitReached;
}
}

$guild = Guild::query()->whereKey($guild->id)->lockForUpdate()->firstOrFail();

if ($guild->user_id !== $user->id) {
throw new GuildModeratorRemoved;
}

if ($handover && ! $guild->members()->whereKey($moderator->id)->exists()) {
throw new GuildModeratorNotMember;
}

$path = $guild->icon_path;

if ($icon instanceof UploadedFile || $removeIcon) {
$this->deleteFiles->retain($path === null ? [] : [$path]);
$path = $icon instanceof UploadedFile ? $this->images->handle([$icon], directory: 'guild-icons')[0]['path'] : null;
}

$guild->update(['description' => $description, 'emoji' => $emoji, 'icon_path' => $path]);
event(new UsersUpdated(DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($guild->user_id), UserUpdate::Guilds));
$guild->update([
'description' => $description,
'emoji' => $emoji,
'icon_path' => $path,
'user_id' => $handover ? $moderator->id : $guild->user_id,
]);

$viewers = DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($user->id);
event(new UsersUpdated($viewers, UserUpdate::Guilds));

if ($handover) {
event(new UsersUpdated($viewers, UserUpdate::Relationships));
}
});
}
}
9 changes: 9 additions & 0 deletions app/Exceptions/GuildModeratorLimitReached.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace App\Exceptions;

use RuntimeException;

final class GuildModeratorLimitReached extends RuntimeException {}
9 changes: 9 additions & 0 deletions app/Exceptions/GuildModeratorNotMember.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace App\Exceptions;

use RuntimeException;

final class GuildModeratorNotMember extends RuntimeException {}
10 changes: 9 additions & 1 deletion app/Http/Controllers/GuildController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use App\Actions\CreateGuild;
use App\Actions\UpdateGuild;
use App\Exceptions\GuildModeratorLimitReached;
use App\Exceptions\GuildModeratorNotMember;
use App\Exceptions\GuildModeratorRemoved;
use App\Http\Requests\CreateGuildRequest;
use App\Http\Requests\ListGuildsRequest;
Expand Down Expand Up @@ -37,6 +39,8 @@ public function store(CreateGuildRequest $request, #[CurrentUser] User $user, Cr
$guild = $action->handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon);
} catch (GuildModeratorRemoved) {
return back()->withErrors(['handle' => 'You cannot reclaim a guild you were removed from.']);
} catch (GuildModeratorLimitReached) {
return back()->withErrors(['handle' => 'You can create up to '.CreateGuildRequest::MAX_PER_USER.' guilds.']);
}

return to_route('guild.show', $guild->handle);
Expand All @@ -63,9 +67,13 @@ public function update(UpdateGuildRequest $request, Guild $guild, #[CurrentUser]
assert($icon instanceof UploadedFile || $icon === null);

try {
$action->handle($guild, $user, $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon'));
$action->handle($guild, $user, $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon'), $request->moderator());
} catch (GuildModeratorRemoved) {
return back()->withErrors(['description' => 'You no longer moderate this guild.']);
} catch (GuildModeratorNotMember) {
return back()->withErrors(['moderator_id' => 'Pick a member of this guild.']);
} catch (GuildModeratorLimitReached) {
return back()->withErrors(['moderator_id' => UpdateGuildRequest::moderatorLimitMessage()]);
}

return to_route('guild.show', $guild->handle);
Expand Down
18 changes: 18 additions & 0 deletions app/Http/Controllers/GuildMemberSuggestionController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\ListGuildMemberSuggestionsRequest;
use App\Models\Guild;
use App\Queries\GuildMemberSuggestionsQuery;
use Illuminate\Http\JsonResponse;

final readonly class GuildMemberSuggestionController
{
public function index(ListGuildMemberSuggestionsRequest $request, Guild $guild, GuildMemberSuggestionsQuery $suggestions): JsonResponse
{
return response()->json(['members' => $suggestions->get($guild, $request->string('q')->value())]);
}
}
2 changes: 1 addition & 1 deletion app/Http/Requests/CreateGuildRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

final class CreateGuildRequest extends FormRequest
{
private const int MAX_PER_USER = 100;
public const int MAX_PER_USER = 100;

public function authorize(Features $features): Response
{
Expand Down
32 changes: 32 additions & 0 deletions app/Http/Requests/ListGuildMemberSuggestionsRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\Feature;
use App\Models\Guild;
use App\Services\Features;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;

final class ListGuildMemberSuggestionsRequest extends FormRequest
{
/**
* Only the moderator picks who takes over, so only they search the members.
*/
public function authorize(Features $features): Response
{
$guild = $this->route('guild');
assert($guild instanceof Guild);

return $features->available(Feature::Guilds, $this->user()) && $guild->user_id === $this->user()?->id
? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string>> */
public function rules(): array
{
return ['q' => ['nullable', 'string', 'max:60']];
}
}
43 changes: 43 additions & 0 deletions app/Http/Requests/UpdateGuildRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@

use App\Enums\Feature;
use App\Models\Guild;
use App\Models\User;
use App\Rules\UnflaggedGuild;
use App\Services\EmojiShortcodes;
use App\Services\Features;
use Closure;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\Validator;

final class UpdateGuildRequest extends FormRequest
{
public static function moderatorLimitMessage(): string
{
return 'This member already moderates '.CreateGuildRequest::MAX_PER_USER.' guilds.';
}

public function authorize(Features $features): Response
{
$guild = $this->route('guild');
Expand All @@ -37,6 +44,7 @@ public function rules(EmojiShortcodes $emoji): array
'images' => ['nullable', 'list', 'max:1'],
'images.*' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048', 'dimensions:max_width=6000,max_height=6000'],
'remove_icon' => ['required', 'boolean'],
'moderator_id' => ['sometimes', 'string', 'uuid'],
];
}

Expand All @@ -50,8 +58,43 @@ public function after(UnflaggedGuild $unflagged): array

$guild = $this->route('guild');
assert($guild instanceof Guild);
$this->validateModerator($validator, $guild);

if ($validator->errors()->isNotEmpty()) {
return;
}

$icon = $this->file('images.0');
$unflagged->validate($validator, $guild->name."\n\n".$this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}];
}

public function moderator(): ?User
{
return $this->filled('moderator_id') ? User::query()->find($this->string('moderator_id')->value()) : null;
}

/**
* Moderation can only go to someone who already joined the guild, wasn't removed from moderating it, and has room for another guild.
*/
private function validateModerator(Validator $validator, Guild $guild): void
{
$moderator = $this->moderator();

if (! $moderator instanceof User || $moderator->id === $this->user()?->id) {
if ($this->filled('moderator_id') && ! $moderator instanceof User) {
$validator->errors()->add('moderator_id', 'Pick a member of this guild.');
}

return;
}

if (! $guild->members()->whereKey($moderator->id)->exists()) {
$validator->errors()->add('moderator_id', 'Pick a member of this guild.');
} elseif (DB::table('guild_moderator_removals')->where('github_id', $moderator->github_id)->where('handle', $guild->handle)->exists()) {
$validator->errors()->add('moderator_id', 'This member was removed as its moderator.');
} elseif (Guild::query()->where('user_id', $moderator->id)->count() >= CreateGuildRequest::MAX_PER_USER) {
$validator->errors()->add('moderator_id', self::moderatorLimitMessage());
}
}
}
51 changes: 51 additions & 0 deletions app/Queries/GuildMemberSuggestionsQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace App\Queries;

use App\Models\Guild;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

final readonly class GuildMemberSuggestionsQuery
{
/**
* The members who could take over moderating the guild: never its current moderator. Without a term, the most recent joiners;
* with one, handles and names that contain it, exact handles and prefixes first.
*
* @return Collection<int, array{id: string, handle: string, name: string, avatar_url: string|null}>
*/
public function get(Guild $guild, string $term, int $limit = 8): Collection
{
$term = Str::of($term)->trim()->ltrim('@')->lower()->value();
$escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term);

return $guild->members()
Comment thread
kachelle marked this conversation as resolved.
Resolved
->select('users.*')
->join('profiles', 'profiles.id', '=', 'users.id')
->when($guild->user_id !== null, fn (Builder $query): Builder => $query->whereKeyNot($guild->user_id))
->when($term !== '', fn (Builder $query): Builder => $query
->where(fn (Builder $query): Builder => $query
->whereRaw("LOWER(profiles.handle) LIKE ? ESCAPE '!'", ["%{$escaped}%"])
->orWhereRaw("LOWER(profiles.name) LIKE ? ESCAPE '!'", ["%{$escaped}%"]))
->orderByRaw(
"CASE WHEN LOWER(profiles.handle) = ? THEN 0 WHEN LOWER(profiles.handle) LIKE ? ESCAPE '!' THEN 1 WHEN LOWER(profiles.name) LIKE ? ESCAPE '!' THEN 2 ELSE 3 END",
[$term, "{$escaped}%", "{$escaped}%"],
))
->orderByPivot('joined_at', 'desc')
->latest('users.id')
->limit($limit)
->get()
->map(fn (User $member): array => [
'id' => $member->id,
'handle' => $member->handle,
'name' => $member->name,
'avatar_url' => $member->avatar_url,
])
->values()
->toBase();
}
}
15 changes: 14 additions & 1 deletion resources/js/components/guild-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { type ReactNode, useRef, useState } from 'react';
import { store, update } from '@/actions/App/Http/Controllers/GuildController';
import { EmojiPickerButton } from '@/components/emoji-picker';
import { GuildIcon } from '@/components/guild-icon';
import { GuildModeratorPicker } from '@/components/guild-moderator-picker';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
Expand Down Expand Up @@ -57,7 +58,7 @@ export function GuildDialog({
</DialogTitle>
<DialogDescription>
{guild
? 'As the moderator, you can change the icon and description.'
? 'As the moderator, you can change the icon and description, or hand moderation to another member.'
: handle
? `Give #${handle} a home. Its commits stay public and keep appearing in the log.`
: 'Create a public group. Its name determines the hashtag that brings commits into the guild.'}
Expand Down Expand Up @@ -230,6 +231,18 @@ export function GuildDialog({
/>
</div>
</div>
{guild && (
<GuildModeratorPicker
handle={guild.handle}
fieldClass={fieldClass}
error={errors.moderator_id}
onChange={() =>
form.current?.clearErrors(
'moderator_id',
)
}
/>
)}
</div>
<DialogFooter className="shrink-0 border-t bg-background p-4 sm:px-6">
<DialogClose asChild>
Expand Down
Loading