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
1 change: 1 addition & 0 deletions KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,7 @@ A signed request sees what the web shows you, such as your own pending commits a
- list guilds as the Guilds page does, 24 a page, searched by name, handle or description, with whether you joined or muted each one and whether it is paused, while guilds are available to you;
- read a guild's board as its page does, 30 threads a page with reply previews, with the guild, its pinned commit and whether you moderate it, while guilds are available to you. The pinned commit also keeps its place in the list, so an app that shows it apart skips it there by its id;
- list a guild's members as its members page does, the moderator first and then the newest joins, 50 a page, with whether you follow each one and whether each one follows you, and the moderator's id, while guilds are available to you;
- create a guild, or claim a paused one, as the Guilds page does, with the same rules and limit of 100, where a guild the moderation flags waits for an admin's review instead, while guilds are available to you;
- join or leave a guild, where joining clears your mute of it, as the Join button does, while guilds are available to you;
- report a guild you don't moderate to the admins, privately, as the Report button does, where reporting it again keeps your first report until an admin dismisses it, while guilds are available to you;
- star or unstar, and list who starred your own commit, newest first, 20 a page;
Expand Down
7 changes: 7 additions & 0 deletions app/Actions/CreateGuild.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ public function handle(User $user, string $handle, string $name, string $descrip
}

if ($flagged) {
// A guild another creation published after validation keeps its hashtag, so nothing waits for review...
$taken = Guild::query()->where('handle', mb_strtolower($handle))->whereNotNull('user_id')->first();

if ($taken instanceof Guild) {
return $taken;
}

assert($icon instanceof UploadedFile || $icon === null);

return $this->submit->handle($user, mb_strtolower($handle), $name, $description, $emoji, $icon, false);
Expand Down
42 changes: 42 additions & 0 deletions app/Http/Controllers/Api/GuildController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@

namespace App\Http\Controllers\Api;

use App\Actions\CreateGuild;
use App\Exceptions\GuildModeratorRemoved;
use App\Http\Requests\CreateApiGuildRequest;
use App\Http\Requests\CreateGuildRequest;
use App\Http\Requests\ListApiGuildsRequest;
use App\Http\Requests\ShowApiGuildRequest;
use App\Http\Resources\CommitResource;
use App\Http\Resources\GuildResource;
use App\Models\Commit;
use App\Models\Guild;
use App\Models\GuildSubmission;
use App\Models\User;
use App\Queries\GuildCommitsQuery;
use App\Queries\GuildsQuery;
use App\Queries\ReplyPreviewsQuery;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\UploadedFile;

final readonly class GuildController
{
Expand All @@ -24,6 +31,33 @@ public function index(ListApiGuildsRequest $request, #[CurrentUser] User $user,
return GuildResource::collection($query->paginate($request->term(), $request->integer('page', 1), $user)->withQueryString());
}

/**
* Creates the guild, or claims a paused one, with the user as its moderator and first member, as the web does. A
* guild the moderation flags waits for an admin instead, so it answers 202 with the web's message.
*/
public function store(CreateApiGuildRequest $request, #[CurrentUser] User $user, CreateGuild $action, GuildsQuery $guilds): JsonResponse
{
$icon = $request->file('images.0');
assert($icon instanceof UploadedFile || $icon === null);

try {
$guild = $action->handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->isFlagged());
} catch (GuildModeratorRemoved) {
return $this->handleRefused(CreateGuildRequest::RECLAIM_REFUSED);
}

if ($guild instanceof GuildSubmission) {
return response()->json(['message' => 'Your guild is waiting for review. It goes live once an admin approves it.'], 202);
Comment thread
WendellAdriel marked this conversation as resolved.
Resolved
}

// Another creation of the same hashtag won the race after validation, and the action leaves it to its moderator...
if ($guild->user_id !== $user->id) {
return $this->handleRefused(CreateGuildRequest::guildMessages()['handle.unique']);
}

return GuildResource::make($guilds->find($guild, $user))->response()->setStatusCode(201);
}

/**
* The guild's board as its page on the web shows it: 30 threads per page, newest first. Everyone gets the pin the
* moderator set beside them, and it keeps its place on the board, which the web's page skips. One snapshot reads the
Expand All @@ -47,4 +81,12 @@ public function show(ShowApiGuildRequest $request, Guild $guild, #[CurrentUser]
'can_moderate' => $guild->user_id === $user->id,
]);
}

/**
* A race lost after validation, answered as the validation would have answered it.
*/
private function handleRefused(string $message): JsonResponse
{
return response()->json(['message' => $message, 'errors' => ['handle' => [$message]]], 422);
}
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/GuildController.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function store(CreateGuildRequest $request, #[CurrentUser] User $user, Cr
try {
$guild = $action->handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->isFlagged());
} catch (GuildModeratorRemoved) {
return back()->withErrors(['handle' => 'You cannot reclaim a guild you were removed from.']);
return back()->withErrors(['handle' => CreateGuildRequest::RECLAIM_REFUSED]);
}

if ($guild instanceof GuildSubmission) {
Expand Down
74 changes: 74 additions & 0 deletions app/Http/Requests/CreateApiGuildRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\Feature;
use App\Models\User;
use App\Rules\FlaggedGuild;
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\Validation\Rules\In;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Validation\Validator;

final class CreateApiGuildRequest extends FormRequest
{
private bool $isFlagged = false;

public function authorize(Features $features): Response
{
return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string|In|Unique>> */
public function rules(EmojiShortcodes $emoji): array
{
return CreateGuildRequest::guildRules($emoji);
}

/** @return list<Closure(Validator): void> */
public function after(FlaggedGuild $flagged): array
{
return [function (Validator $validator) use ($flagged): void {
if ($validator->errors()->isNotEmpty()) {
return;
}

$user = $this->user();
assert($user instanceof User);
$icon = $this->file('images.0');
$this->isFlagged = CreateGuildRequest::validateNewGuild($validator, $flagged, $user, $this->string('handle')->value(), $this->string('name')->value(), $this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}];
}

/**
* Whether the moderation flagged the guild, so it waits for an admin instead of being published.
*/
public function isFlagged(): bool
{
return $this->isFlagged;
}

/** @return array<string, string> */
public function messages(): array
{
return CreateGuildRequest::guildMessages();
}

public function prepareForValidation(): void
{
if (! $this->has('handle') && is_string($this->input('name'))) {
$this->merge(['handle' => CreateGuildRequest::hashtagOf($this->string('name')->value())]);
}

if (is_string($this->input('handle'))) {
$this->merge(['handle' => $this->string('handle')->trim()->lower()->value()]);
}
}
}
100 changes: 69 additions & 31 deletions app/Http/Requests/CreateGuildRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Enums\Feature;
use App\Models\Guild;
use App\Models\GuildSubmission;
use App\Models\User;
use App\Rules\FlaggedGuild;
use App\Services\EmojiShortcodes;
use App\Services\Features;
Expand All @@ -15,24 +16,26 @@
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Validation\Validator;

final class CreateGuildRequest extends FormRequest
{
public const string RECLAIM_REFUSED = 'You cannot reclaim a guild you were removed from.';

private const int MAX_PER_USER = 100;

private bool $isFlagged = false;

public function authorize(Features $features): Response
{
return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string|In|Unique>> */
public function rules(EmojiShortcodes $emoji): array
/**
* The rules a new guild follows, wherever it's created.
*
* @return array<string, list<string|In|Unique>>
*/
public static function guildRules(EmojiShortcodes $emoji): array
{
return [
'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', Rule::unique('guilds', 'handle')->whereNotNull('user_id')],
Expand All @@ -44,6 +47,59 @@ public function rules(EmojiShortcodes $emoji): array
];
}

/**
* Refuses a name that doesn't match the hashtag, a guild the user was removed from, and more guilds than the user
* may have, counting the ones waiting for review. A guild that passes is moderated, and the answer says whether the
* moderation flagged it.
*/
public static function validateNewGuild(Validator $validator, FlaggedGuild $flagged, User $user, string $handle, string $name, string $description, ?UploadedFile $icon): bool
{
if (self::hashtagOf($name) !== $handle) {
$validator->errors()->add('name', "Guild display name doesn't match hashtag");
}

if (DB::table('guild_moderator_removals')->where('github_id', $user->github_id)->where('handle', $handle)->exists()) {
$validator->errors()->add('handle', self::RECLAIM_REFUSED);
}

$guilds = Guild::query()->where('user_id', $user->id);
$submissions = GuildSubmission::query()->where('user_id', $user->id)->where('handle', '!=', $handle)->whereNotIn('handle', (clone $guilds)->select('handle'));

if ($guilds->count() + $submissions->count() >= self::MAX_PER_USER) {
Comment thread
WendellAdriel marked this conversation as resolved.
Resolved
$validator->errors()->add('handle', 'You can create up to '.self::MAX_PER_USER.' guilds.');
}

return $validator->errors()->isEmpty() && $flagged->validate($validator, $name."\n\n".$description, $icon);
}

/**
* The hashtag a display name stands for: its letters, numbers and underscores, lowercased.
*/
public static function hashtagOf(string $name): string
{
return Str::of($name)->replaceMatches('/[^\p{L}\p{M}\p{N}_]+/u', '')->lower()->value();
}

/** @return array<string, string> */
public static function guildMessages(): array
{
return [
'handle.unique' => 'A guild already uses this hashtag. Choose a different display name.',
'handle.regex' => 'Use a display name whose hashtag starts with a letter and contains only letters, numbers and underscores.',
];
}

public function authorize(Features $features): Response
{
return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string|In|Unique>> */
public function rules(EmojiShortcodes $emoji): array
{
return self::guildRules($emoji);
}

/** @return list<Closure(Validator): void> */
public function after(FlaggedGuild $flagged): array
{
Expand All @@ -52,25 +108,10 @@ public function after(FlaggedGuild $flagged): array
return;
}

if ($this->string('name')->replaceMatches('/[^\p{L}\p{M}\p{N}_]+/u', '')->lower()->value() !== $this->string('handle')->value()) {
$validator->errors()->add('name', "Guild display name doesn't match hashtag");
}

if (DB::table('guild_moderator_removals')->where('github_id', $this->user()?->github_id)->where('handle', $this->string('handle')->value())->exists()) {
$validator->errors()->add('handle', 'You cannot reclaim a guild you were removed from.');
}

$guilds = Guild::query()->where('user_id', $this->user()?->id);
$submissions = GuildSubmission::query()->where('user_id', $this->user()?->id)->where('handle', '!=', $this->string('handle')->value())->whereNotIn('handle', (clone $guilds)->select('handle'));

if ($guilds->count() + $submissions->count() >= self::MAX_PER_USER) {
$validator->errors()->add('handle', 'You can create up to '.self::MAX_PER_USER.' guilds.');
}

if ($validator->errors()->isEmpty()) {
$icon = $this->file('images.0');
$this->isFlagged = $flagged->validate($validator, $this->string('name')->value()."\n\n".$this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}
$user = $this->user();
assert($user instanceof User);
$icon = $this->file('images.0');
$this->isFlagged = self::validateNewGuild($validator, $flagged, $user, $this->string('handle')->value(), $this->string('name')->value(), $this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}];
}

Expand All @@ -85,16 +126,13 @@ public function isFlagged(): bool
/** @return array<string, string> */
public function messages(): array
{
return [
'handle.unique' => 'A guild already uses this hashtag. Choose a different display name.',
'handle.regex' => 'Use a display name whose hashtag starts with a letter and contains only letters, numbers and underscores.',
];
return self::guildMessages();
}

public function prepareForValidation(): void
{
if (! $this->has('handle') && is_string($this->input('name'))) {
$this->merge(['handle' => $this->string('name')->replaceMatches('/[^\p{L}\p{M}\p{N}_]+/u', '')->lower()->value()]);
$this->merge(['handle' => self::hashtagOf($this->string('name')->value())]);
}

if (is_string($this->input('handle'))) {
Expand Down
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,9 @@

// Guilds: the directory the web's Guilds page lists, a guild's board and its members...
Route::get('guilds', [GuildController::class, 'index'])->name('api-guild.index');
Route::post('guilds', [GuildController::class, 'store'])
->middleware([PreventPostingInTimeout::class, 'throttle:10,1,guilds:'])
->name('api-guild.store');
Route::get('guilds/{guild:handle}', [GuildController::class, 'show'])->name('api-guild.show');
Route::get('guilds/{guild:handle}/members', [GuildMembershipController::class, 'index'])->name('api-guild-membership.index');

Expand Down
Loading
Loading