From eb9ba18b37c763cadac97a9a70f02b9d332f3615 Mon Sep 17 00:00:00 2001 From: Shane Smith Date: Fri, 27 Nov 2026 05:28:08 +1030 Subject: [PATCH] [Guilds] Create, Edit, Pin, Unpin, Upload Logo --- app/Devnull/Client.php | 117 ++++++- app/Devnull/CommitMenu.php | 10 +- app/Devnull/Data/GuildSaved.php | 24 ++ app/Devnull/RowInputs.php | 2 + app/NativeComponents/Guild.php | 60 +++- app/NativeComponents/GuildForm.php | 319 ++++++++++++++++++ app/NativeComponents/Guilds.php | 8 + resources/views/native/guild-form.blade.php | 72 ++++ resources/views/native/guilds.blade.php | 4 + .../native/partials/commit-actions.blade.php | 2 +- .../native/partials/guild-header.blade.php | 6 +- .../views/native/partials/guild-row.blade.php | 11 +- routes/mobile.php | 4 + tests/Feature/Devnull/GuildWritesTest.php | 124 +++++++ tests/Feature/Screens/GuildBoardPinTest.php | 133 ++++++++ tests/Feature/Screens/GuildFormTest.php | 289 ++++++++++++++++ tests/Feature/Screens/GuildMenuTest.php | 15 + tests/Feature/Screens/GuildsTest.php | 10 + 18 files changed, 1200 insertions(+), 10 deletions(-) create mode 100644 app/Devnull/Data/GuildSaved.php create mode 100644 app/NativeComponents/GuildForm.php create mode 100644 resources/views/native/guild-form.blade.php create mode 100644 tests/Feature/Devnull/GuildWritesTest.php create mode 100644 tests/Feature/Screens/GuildBoardPinTest.php create mode 100644 tests/Feature/Screens/GuildFormTest.php diff --git a/app/Devnull/Client.php b/app/Devnull/Client.php index 24741ae6..02e48f3e 100644 --- a/app/Devnull/Client.php +++ b/app/Devnull/Client.php @@ -10,6 +10,7 @@ use App\Devnull\Data\Guild; use App\Devnull\Data\GuildBoard; use App\Devnull\Data\GuildMembers; +use App\Devnull\Data\GuildSaved; use App\Devnull\Data\IncomingCall; use App\Devnull\Data\MessageVoice; use App\Devnull\Data\Notification; @@ -544,6 +545,59 @@ public function reportGuild(string $handle, string $details): void $this->send('POST', 'guilds/'.rawurlencode($handle).'/reports', payload: ['details' => $details]); } + /** + * Creates a guild, as the web's Create a guild does: devnull makes its + * hashtag from the name, and you become its moderator and first member. + * An uploaded icon goes as multipart, in place of the emoji. + */ + public function createGuild(string $name, string $description, string $emoji, ?DraftImage $icon = null): GuildSaved + { + $payload = ['name' => $name, 'description' => $description, 'emoji' => $emoji]; + + $response = $icon === null + ? $this->send('POST', 'guilds', payload: $payload) + : $this->sendSignedOrFail($this->signedWithIcon('guilds', $payload, $icon)); + + $this->cache->forget('guilds'); + + return $this->guildSaved($response); + } + + /** + * Edits a guild you moderate, as the web's Edit guild does. Its hashtag + * stays. $removeIcon takes the uploaded icon off, back to the emoji. A new + * icon goes as multipart, which PHP only reads from a POST, so it goes as + * a POST that devnull takes as the PUT it was signed as. + */ + public function updateGuild(string $handle, string $name, string $description, string $emoji, bool $removeIcon, ?DraftImage $icon = null): GuildSaved + { + $path = 'guilds/'.rawurlencode($handle); + $payload = ['name' => $name, 'description' => $description, 'emoji' => $emoji, 'remove_icon' => $removeIcon]; + + $response = $icon === null + ? $this->send('PUT', $path, payload: $payload) + : $this->sendSignedOrFail($this->signedWithIcon($path, $payload, $icon, 'PUT')); + + $this->cache->forget('guilds'); + $this->cache->forget($path); + + return $this->guildSaved($response); + } + + /** + * Pins a commit to the top of a guild's board, as its moderator does on + * the web, in place of the one pinned before. + */ + public function pinGuildCommit(string $handle, string $commitId): void + { + $this->send('PUT', self::guildPinPath($handle, $commitId)); + } + + public function unpinGuildCommit(string $handle, string $commitId): void + { + $this->send('DELETE', self::guildPinPath($handle, $commitId)); + } + /** * A page of your Remotes inbox, newest first, for the web's Open, Fetched * or Stashed tab, continuing before a conversation. @@ -956,11 +1010,66 @@ private function signedWithVoice(string $path, string $clientId, ?int $replyToId } /** - * The payload part, then each file, with the files' SHA-256 signed on a line before the body. + * Signs a guild write with its uploaded icon, as one image part beside the payload. + * + * @param array $payload + */ + private function signedWithIcon(string $path, array $payload, DraftImage $icon, string $signedMethod = 'POST'): SignedRequest + { + return $this->signedMultipart($this->target($path, []), self::body($payload), [ + ['images[]', 'image-1.'.substr($icon->mimeType, 6), $icon->mimeType, (string) file_get_contents($icon->path)], + ], $signedMethod); + } + + /** + * Sends a request signed here, failing as send() does when devnull refuses it or can't be reached. + */ + private function sendSignedOrFail(SignedRequest $request): Response + { + try { + $response = self::sendSigned($request); + } catch (ConnectionException) { + throw ApiException::couldNotConnect($this->baseUrl); + } + + if (! $response->successful()) { + throw ApiException::fromResponse($response); + } + + if (! self::answeredByDevnull($response, $request->method)) { + throw ApiException::unexpectedAnswer($this->baseUrl, $response->status()); + } + + return $response; + } + + /** + * The guild devnull saved, or, answered 202, the message saying it waits for an admin. + */ + private function guildSaved(Response $response): GuildSaved + { + $json = $this->json($response); + + if ($response->status() === 202) { + return new GuildSaved(null, is_string($json['message'] ?? null) ? $json['message'] : ''); + } + + return new GuildSaved(Guild::fromArray(is_array($json['data'] ?? null) ? $json['data'] : $json)); + } + + private static function guildPinPath(string $handle, string $commitId): string + { + return 'guilds/'.rawurlencode($handle).'/commits/'.rawurlencode($commitId).'/pin'; + } + + /** + * The payload part, then each file, with the files' SHA-256 signed on a + * line before the body. Signed as anything but a POST, it still goes as a + * POST, with devnull told the method it was signed as. * * @param list $files each one's field, filename, type and bytes */ - private function signedMultipart(string $target, string $payload, array $files): SignedRequest + private function signedMultipart(string $target, string $payload, array $files, string $signedMethod = 'POST'): SignedRequest { $boundary = 'devnull-'.bin2hex(random_bytes(16)); @@ -976,9 +1085,11 @@ private function signedMultipart(string $target, string $payload, array $files): $hashes = implode(',', array_map(fn (array $file): string => hash('sha256', $file[3]), $files)); + $headers = $this->sign($signedMethod, $target, $hashes."\n".$payload, RequestSigner::ImagesNamespace); + return new SignedRequest( $this->origin().$target, - $this->sign('POST', $target, $hashes."\n".$payload, RequestSigner::ImagesNamespace), + $signedMethod === 'POST' ? $headers : [...$headers, 'X-HTTP-Method-Override' => $signedMethod], 'POST', $body."--{$boundary}--\r\n", "multipart/form-data; boundary={$boundary}", diff --git a/app/Devnull/CommitMenu.php b/app/Devnull/CommitMenu.php index 491aeecf..d11c8565 100644 --- a/app/Devnull/CommitMenu.php +++ b/app/Devnull/CommitMenu.php @@ -11,7 +11,9 @@ * What More holds, on the right of a commit's action row (see * partials/commit-actions): Share link on every commit; Pin to profile or * Unpin from profile on your own published commit, not a reply nor one posted - * in a guild, which devnull won't pin to a profile; then, after a + * in a guild, which devnull won't pin to a profile; Pin to board or Unpin from + * board on a top-level commit of a guild's board, for its moderator + * ($boardPinned says whether it's the one pinned there); then, after a * divider, Report commit on someone else's published commit, or Delete commit * on yours. An organization's commit is yours while you're a member, whoever * posted it (see Ownership), so every member gets Delete, as on the web. Only @@ -23,7 +25,7 @@ final class CommitMenu /** * @return list */ - public static function items(Commit $commit, Ownership $ownership): array + public static function items(Commit $commit, Ownership $ownership, ?bool $boardPinned = null): array { $isOwn = $ownership->owns($commit); $items = []; @@ -34,6 +36,10 @@ public static function items(Commit $commit, Ownership $ownership): array $items[] = self::item($commit, 'pin', $commit->isPinned ? 'Unpin from profile' : 'Pin to profile', Lucide::Pin, 'togglePin'); } + if ($boardPinned !== null) { + $items[] = self::item($commit, 'board-pin', $boardPinned ? 'Unpin from board' : 'Pin to board', $boardPinned ? Lucide::PinOff : Lucide::Pin, 'toggleBoardPin'); + } + if ($ownership->isSignedIn() && ! $isOwn && $commit->isApproved()) { $items[] = NavAction::divider(); $items[] = self::item($commit, 'report', 'Report commit', Lucide::Flag, 'reportCommit'); diff --git a/app/Devnull/Data/GuildSaved.php b/app/Devnull/Data/GuildSaved.php new file mode 100644 index 00000000..4f931117 --- /dev/null +++ b/app/Devnull/Data/GuildSaved.php @@ -0,0 +1,24 @@ +heldMessage !== null; + } +} diff --git a/app/Devnull/RowInputs.php b/app/Devnull/RowInputs.php index 41b62a77..843a5367 100644 --- a/app/Devnull/RowInputs.php +++ b/app/Devnull/RowInputs.php @@ -49,6 +49,8 @@ public static function for(Commit $commit, array $scope): array 'poll' => [$scope['pollChoices'][$commit->id] ?? null, in_array($commit->id, $scope['voting'] ?? [], true)], 'selected' => ($scope['selectedCommit'] ?? null) === $commit->id, 'video' => $commit->linkPreview?->embed === null ? null : VideoDetails::card($commit->linkPreview), + // On a guild's board, its moderator's More pins or unpins it. + 'boardPin' => ($scope['pinsToBoard'] ?? false) ? ($scope['boardPinnedId'] ?? null) === $commit->id : null, // A poll's Vote button wears your lane colour. 'colour' => $scope['myColour'] ?? null, ]; diff --git a/app/NativeComponents/Guild.php b/app/NativeComponents/Guild.php index 002ed2f2..5d382267 100644 --- a/app/NativeComponents/Guild.php +++ b/app/NativeComponents/Guild.php @@ -13,6 +13,7 @@ use App\Devnull\RowCache; use App\Devnull\Stash; use App\Devnull\Timeline; +use App\Devnull\Toasts; use App\Icons\Lucide; use App\Models\PendingWrite; use App\NativeComponents\Concerns\DrawsSkeletonFirst; @@ -158,7 +159,8 @@ public function navTitle(): string /** * β‹―, as on someone else's profile: Share guild, then Mute or Unmute while * you haven't joined, as the web hides Mute once you join. Commit and Join - * are in the header, as Remote and Follow are on a profile. + * are in the header, as Remote and Follow are on a profile, and so is the + * moderator's Edit. The moderator gets no Report. */ public function navigationOptions(): ?NavBarOptions { @@ -194,6 +196,23 @@ public function navigationOptions(): ?NavBarOptions ); } + /** + * The header's Edit, for the guild's moderator: the guild form, filled in with what this page shows. + */ + public function editGuild(): void + { + if ($this->guild === null || ! $this->canModerate) { + return; + } + + $this->openInTab('/guilds/'.rawurlencode($this->guild->handle).'/edit', [ + 'name' => $this->guild->name, + 'description' => $this->guild->description, + 'emoji' => $this->guild->emoji, + 'iconUrl' => $this->guild->iconUrl, + ]); + } + /** * Report guild, from the menu: its sheet, empty. devnull doesn't take a report from the guild's moderator. */ @@ -349,6 +368,42 @@ public function toggleJoined(): void } } + /** + * Pin to board or Unpin from board, from a commit's More, for the guild's + * moderator. Once devnull answers, the commit takes the pinned place, or + * goes back to its own, and a toast says so, as Pin to profile does. The + * board is asked for again behind it, so what's kept catches up. + */ + public function toggleBoardPin(string $id): void + { + $commit = $this->shownCommit($id); + + if ($this->guild === null || ! $this->canModerate || $commit === null || $commit->parentId !== null) { + return; + } + + $handle = $this->guild->handle; + $pinning = $this->pinnedId !== $id; + + $done = $this->attempt(function (Client $devnull) use ($handle, $id, $pinning): bool { + $pinning ? $devnull->pinGuildCommit($handle, $id) : $devnull->unpinGuildCommit($handle, $id); + + return true; + }); + + if ($done !== true) { + return; + } + + $this->pinned = $pinning ? $commit : null; + $this->pinnedId = $pinning ? $id : null; + + Toasts::say($pinning ? 'Commit pinned to the board.' : 'Commit unpinned.', short: true); + + // Asked again even while an earlier ask is out, whose answer would put the old pin back. + $this->refresh($this->boardPath(), [], fn (array $json) => $this->takeBoard($json), again: true); + } + /** * The member count: who's in the guild, titled with its name. */ @@ -418,6 +473,9 @@ public function render(): View 'isEmpty' => $pinned === null && $boardCommits === [], // Everything on the board was posted in this guild, so none of it says so. 'hidesGuildBadge' => true, + // Its moderator pins and unpins from a commit's More (see CommitMenu). + 'pinsToBoard' => $this->canModerate, + 'boardPinnedId' => $this->pinnedId, ]); } diff --git a/app/NativeComponents/GuildForm.php b/app/NativeComponents/GuildForm.php new file mode 100644 index 00000000..28bb260f --- /dev/null +++ b/app/NativeComponents/GuildForm.php @@ -0,0 +1,319 @@ +isEditing()) { + return; + } + + $this->name = (string) $this->data('name', ''); + $this->description = (string) $this->data('description', ''); + $this->emoji = (string) $this->data('emoji', '') ?: self::DefaultEmoji; + $iconUrl = $this->data('iconUrl'); + $this->iconUrl = is_string($iconUrl) && $iconUrl !== '' ? $iconUrl : null; + } + + public function navTitle(): string + { + return $this->isEditing() ? 'Edit guild' : 'Create a guild'; + } + + /** + * Whether this edits a guild, opened at its handle, rather than creating one. + */ + public function isEditing(): bool + { + return $this->editedHandle() !== ''; + } + + /** + * The hashtag the name makes, as the web makes it: its letters, numbers and underscores, lowercased. + */ + public function hashtag(): string + { + return mb_strtolower((string) preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '', $this->name)); + } + + public function openEmojiPicker(): void + { + $this->emojiPickerOpen = true; + } + + /** + * An emoji from the picker becomes the icon, in place of any picked image. One devnull doesn't know is refused. + */ + public function emojiPicked(string $emoji): void + { + $this->emojiPickerOpen = false; + $known = ReactionEmoji::forDevnull($emoji); + + if ($known === null) { + $this->formError = self::EmojiRefused; + + return; + } + + $this->emoji = $known; + $this->formError = null; + $this->removeIcon = true; + $this->dropIcon(); + } + + public function emojiPickerClosed(): void + { + $this->emojiPickerOpen = false; + } + + /** + * Upload image: one photo from the library. + */ + public function pickIcon(): void + { + Camera::pickImages('images', false, 1)->start(); + } + + /** + * The photo the library handed back becomes the icon, unless devnull wouldn't take it: over 2 MB, or not a + * JPEG, PNG or WebP. + * + * @param list $files + */ + #[On(MediaSelected::class)] + public function photosPicked(array $files = []): void + { + $path = is_array($files[0] ?? null) && is_string($files[0]['path'] ?? null) ? $files[0]['path'] : ''; + + // The picker was cancelled, or handed back nothing: the icon stays as it was, with nothing to say. + if ($path === '') { + return; + } + + try { + $image = app(DraftImages::class)->keep($path); + } catch (InvalidDraftImage) { + $this->formError = self::IconTooBig; + + return; + } + + if ((int) filesize($image->path) > self::IconMaxBytes) { + app(DraftImages::class)->discard([$image]); + $this->formError = self::IconTooBig; + + return; + } + + $this->dropIcon(); + $this->icon = $image; + $this->formError = null; + } + + /** + * Create guild: checked here first as the web checks it, then sent once. + */ + public function save(): void + { + if ($this->saving || trim($this->name) === '' || trim($this->description) === '') { + return; + } + + $this->formError = $this->refusal(); + + if ($this->formError !== null) { + return; + } + + $this->saving = true; + + try { + $saved = $this->isEditing() + ? app(Client::class)->updateGuild($this->editedHandle(), trim($this->name), trim($this->description), $this->emoji, $this->removeIcon && $this->icon === null, $this->icon) + : app(Client::class)->createGuild(trim($this->name), trim($this->description), $this->emoji, $this->icon); + } catch (Unauthenticated $exception) { + $this->signOut($exception); + + return; + } catch (ApiException $exception) { + // No longer this guild's moderator, or no such guild any more: nothing here to fix, so back to it. + if ($this->isEditing() && $exception->status === 404) { + Toasts::failed($exception->firstError()); + $this->back(); + + return; + } + + $this->formError = $exception->firstError(); + $this->saving = false; + + return; + } catch (KeychainUnavailable $exception) { + $this->formError = $exception->getMessage(); + $this->saving = false; + + return; + } + + $this->dropIcon(); + $this->saved($saved); + } + + public function render(): View + { + $hashtag = $this->isEditing() ? $this->editedHandle() : $this->hashtag(); + + return view('native.guild-form', [ + 'hashtag' => $hashtag, + 'isEditing' => $this->isEditing(), + 'mark' => new GuildData(handle: $hashtag, name: $this->name, emoji: $this->emoji, iconUrl: $this->icon?->path ?? ($this->removeIcon ? null : $this->iconUrl)), + 'myColour' => $this->myColour(), + ]); + } + + /** + * Why the web wouldn't send this name, or null when it would. + */ + private function refusal(): ?string + { + if (mb_strlen(trim($this->name)) > self::NameMaxLength) { + return self::NameTooLong; + } + + if ($this->isEditing() && $this->hashtag() !== mb_strtolower($this->editedHandle())) { + return self::HashtagChanged; + } + + if (preg_match('/^\p{L}[\p{L}\p{M}\p{N}_]{0,59}$/u', $this->hashtag()) !== 1) { + return self::HashtagRefused; + } + + return null; + } + + /** + * The new guild opens in this screen's place, or a held one says so and the screen goes. + */ + private function saved(GuildSaved $saved): void + { + if ($saved->isHeld()) { + Toasts::say((string) $saved->heldMessage); + } + + if ($this->isEditing() || $saved->guild === null) { + $this->back(); + + return; + } + + $this->replace($this->tabRoot().'/guilds/'.rawurlencode($saved->guild->handle)); + } + + private function editedHandle(): string + { + return (string) $this->param('handle', ''); + } + + /** + * The picked image comes off the form, and off the phone. + */ + private function dropIcon(): void + { + if ($this->icon !== null) { + app(DraftImages::class)->discard([$this->icon]); + $this->icon = null; + } + } +} diff --git a/app/NativeComponents/Guilds.php b/app/NativeComponents/Guilds.php index 0ef323c0..eae199db 100644 --- a/app/NativeComponents/Guilds.php +++ b/app/NativeComponents/Guilds.php @@ -100,6 +100,14 @@ public function browseAll(): void $this->ask(again: true); } + /** + * Create a guild, as the web's Guilds page offers above its list: the guild form, beneath this tab. + */ + public function createGuild(): void + { + $this->openInTab('/guilds/_new'); + } + public function loadMore(): void { if ($this->nextPage === null) { diff --git a/resources/views/native/guild-form.blade.php b/resources/views/native/guild-form.blade.php new file mode 100644 index 00000000..2ecf7802 --- /dev/null +++ b/resources/views/native/guild-form.blade.php @@ -0,0 +1,72 @@ +{{-- + The web's guild dialog as a screen (see App\NativeComponents\GuildForm): what a guild is, the hashtag the name makes, + the display name, the description, and the icon, an emoji from the picker or an image from your photos. The button + rides above the keyboard in the bottom bar, with devnull's reason beside it when it says no, as on New org. +--}} +@use('App\Icons\Lucide') +@use('App\NativeComponents\GuildForm') + + + + + + {{ $isEditing ? 'As the moderator, you can change the display name, icon and description.' : 'Create a public group. Its name determines the hashtag that brings commits into the guild.' }} + + {{ $hashtag === '' ? 'Your hashtag appears here' : '#'.$hashtag }} + + + Guild display name + + + + Spaces and decoration are okay. Matching hashtags link to this guild. + + + + + + Icon + + + + @include('native.partials.guild-mark', ['guild' => $mark, 'size' => 48, 'ref' => 'guild-form-mark']) + + + Emoji + Upload image + + Choose an emoji or upload an image. JPEG, PNG or WebP, up to 2 MB. An upload replaces the emoji. + + + {{-- The bottom bar sits over the end of the form, so the form clears it and the home indicator. --}} + + + + + + + + + {{ $formError ?? '' }} + + {{ $isEditing ? 'Save changes' : 'Create guild' }} + + + + + diff --git a/resources/views/native/guilds.blade.php b/resources/views/native/guilds.blade.php index 05f5b848..81cd4623 100644 --- a/resources/views/native/guilds.blade.php +++ b/resources/views/native/guilds.blade.php @@ -35,6 +35,10 @@ class="w-full text-theme-ink" Search names, #handles, and descriptions. + + Start a public group. + Create a guild + diff --git a/resources/views/native/partials/commit-actions.blade.php b/resources/views/native/partials/commit-actions.blade.php index 5118560f..7938bf66 100644 --- a/resources/views/native/partials/commit-actions.blade.php +++ b/resources/views/native/partials/commit-actions.blade.php @@ -124,7 +124,7 @@ - + diff --git a/resources/views/native/partials/guild-header.blade.php b/resources/views/native/partials/guild-header.blade.php index e0102f81..5e36c71f 100644 --- a/resources/views/native/partials/guild-header.blade.php +++ b/resources/views/native/partials/guild-header.blade.php @@ -1,6 +1,7 @@ {{-- A guild's header, at the top of its board (see guild.blade.php), in the web's words: its icon or emoji (see - guild-mark) with Commit and Join or Leave beside it, as a profile has Remote and Follow, its name, + guild-mark) with Commit and Join or Leave beside it, as a profile has Remote and Follow, and Edit between them for + its moderator, as the web's pencil shows them it's theirs. Then its name, "#handle Β· Public guild Β· N members", the count opening its members, what it's about, then how to post there, or that it's paused while it has no moderator. Commit, which posts to the board, shows while the guild takes posts. --}} @@ -16,6 +17,9 @@ @unless ($guild->isPaused) Commit @endunless + @if ($canModerate) + Edit + @endif @if ($guild->isJoined) Leave @else diff --git a/resources/views/native/partials/guild-row.blade.php b/resources/views/native/partials/guild-row.blade.php index 98f18ff9..6f02386d 100644 --- a/resources/views/native/partials/guild-row.blade.php +++ b/resources/views/native/partials/guild-row.blade.php @@ -1,10 +1,11 @@ {{-- - A guild in the directory, as the web's card shows it: its uploaded icon, or its emoji (see guild-mark). + A guild in the directory, as the web's card shows it: its uploaded icon, or its emoji (see guild-mark). One + you've joined has a mark at the end of its row, apart from anything about moderating it, which doesn't need joining. Tapped, it opens the guild's screen (see OpensGuilds). --}} @php($members = \App\Devnull\Display::count($guild->memberCount, 'member', 'members')) - + @include('native.partials.guild-mark', ['guild' => $guild, 'size' => 40, 'ref' => 'guild-mark-'.$guild->handle]) @@ -16,4 +17,10 @@ @endif {{ $members }} + {{-- Kept on every row, so a description wraps in the same place whether you've joined or not. --}} + + @if ($guild->isJoined) + + @endif + diff --git a/routes/mobile.php b/routes/mobile.php index 3aa1fa4d..3b1c7c9a 100644 --- a/routes/mobile.php +++ b/routes/mobile.php @@ -10,6 +10,7 @@ use App\NativeComponents\Conversation; use App\NativeComponents\FeedWorkspace; use App\NativeComponents\Guild; +use App\NativeComponents\GuildForm; use App\NativeComponents\GuildMembers; use App\NativeComponents\Guilds; use App\NativeComponents\Launch; @@ -84,7 +85,10 @@ Route::native("{$tab}/scheduled", ScheduledCommits::class); Route::native("{$tab}/search", Search::class); Route::native("{$tab}/guilds", Guilds::class); + // A handle starts with a letter, so no guild can be "_new", where "new" would hide a guild of that name. + Route::native("{$tab}/guilds/_new", GuildForm::class); Route::native("{$tab}/guilds/{handle}", Guild::class); Route::native("{$tab}/guilds/{handle}/members", GuildMembers::class); + Route::native("{$tab}/guilds/{handle}/edit", GuildForm::class); } }); diff --git a/tests/Feature/Devnull/GuildWritesTest.php b/tests/Feature/Devnull/GuildWritesTest.php new file mode 100644 index 00000000..a0c9caf3 --- /dev/null +++ b/tests/Feature/Devnull/GuildWritesTest.php @@ -0,0 +1,124 @@ + 'http://devnull.test']); + fakeKeychain(testSeed()); +}); + +/** + * The one request devnull was sent. + */ +function sentGuildWrite(): Request +{ + $recorded = Http::recorded(); + + expect($recorded)->toHaveCount(1); + + return $recorded[0][0]; +} + +it('creates a guild as signed JSON', function () { + fakeApi(['POST /api/v1/guilds' => [['data' => guildJson(['handle' => 'rustlang', 'name' => 'Rust Lang'])], 201]]); + + $saved = app(Client::class)->createGuild('Rust Lang', 'All about Rust.', 'πŸ¦€'); + + $request = sentGuildWrite(); + + expect($request->method())->toBe('POST') + ->and($request->url())->toBe('http://devnull.test/api/v1/guilds') + ->and($request->data())->toBe(['name' => 'Rust Lang', 'description' => 'All about Rust.', 'emoji' => 'πŸ¦€']) + ->and($saved->guild?->handle)->toBe('rustlang') + ->and($saved->isHeld())->toBeFalse(); +}); + +it('creates a guild with its icon as multipart', function () { + fakeApi(['POST /api/v1/guilds' => [['data' => guildJson()], 201]]); + $icon = new DraftImage(testPhoto(), 'image/png', 40, 30); + + app(Client::class)->createGuild('Rust', 'All about Rust.', 'πŸ¦€', $icon); + + $parts = multipartParts(sentGuildWrite()); + + expect(array_column($parts, 'name'))->toBe(['payload', 'images[]']) + ->and(json_decode($parts[0]['contents'], true))->toBe(['name' => 'Rust', 'description' => 'All about Rust.', 'emoji' => 'πŸ¦€']) + ->and($parts[1]['contents'])->toBe(file_get_contents($icon->path)); +}); + +it('says a held guild is waiting for review', function () { + fakeApi(['POST /api/v1/guilds' => [['message' => 'Your guild is waiting for review. It goes live once an admin approves it.'], 202]]); + + $saved = app(Client::class)->createGuild('Rust', 'All about Rust.', 'πŸ¦€'); + + expect($saved->isHeld())->toBeTrue() + ->and($saved->heldMessage)->toBe('Your guild is waiting for review. It goes live once an admin approves it.') + ->and($saved->guild)->toBeNull(); +}); + +it('edits a guild as a signed JSON PUT', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['data' => guildJson(['description' => 'Fearless.'])]]]); + + $saved = app(Client::class)->updateGuild('rust', 'Rust', 'Fearless.', 'πŸ¦€', removeIcon: true); + + $request = sentGuildWrite(); + + expect($request->method())->toBe('PUT') + ->and($request->data())->toBe(['name' => 'Rust', 'description' => 'Fearless.', 'emoji' => 'πŸ¦€', 'remove_icon' => true]) + ->and($saved->guild?->description)->toBe('Fearless.'); +}); + +it('edits a guild with a new icon as a POST that overrides to PUT, signed as PUT', function () { + fakeApi(['POST /api/v1/guilds/rust' => [['data' => guildJson()]]]); + $icon = new DraftImage(testPhoto(), 'image/png', 40, 30); + + app(Client::class)->updateGuild('rust', 'Rust', 'Fearless.', 'πŸ¦€', removeIcon: false, icon: $icon); + + $request = sentGuildWrite(); + $parts = multipartParts($request); + $message = RequestSigner::message( + $request->header('X-Devnull-Timestamp')[0], + $request->header('X-Devnull-Nonce')[0], + 'PUT', + '/api/v1/guilds/rust', + hash_file('sha256', $icon->path)."\n".$parts[0]['contents'], + ); + + expect($request->method())->toBe('POST') + ->and($request->header('X-HTTP-Method-Override'))->toBe(['PUT']) + ->and(array_column($parts, 'name'))->toBe(['payload', 'images[]']) + ->and(json_decode($parts[0]['contents'], true))->toBe(['name' => 'Rust', 'description' => 'Fearless.', 'emoji' => 'πŸ¦€', 'remove_icon' => false]) + ->and($request->header('X-SSH-Signature')[0])->toBe(testKey()->sign($message, 'devnull-api-images')); +}); + +it('pins and unpins a commit on the board', function () { + fakeApi([ + 'PUT /api/v1/guilds/rust/commits/c1/pin' => [null, 204], + 'DELETE /api/v1/guilds/rust/commits/c1/pin' => [null, 204], + ]); + + app(Client::class)->pinGuildCommit('rust', 'c1'); + app(Client::class)->unpinGuildCommit('rust', 'c1'); + + expect(Http::recorded()->map(fn (array $pair): string => $pair[0]->method().' '.$pair[0]->url())->all())->toBe([ + 'PUT http://devnull.test/api/v1/guilds/rust/commits/c1/pin', + 'DELETE http://devnull.test/api/v1/guilds/rust/commits/c1/pin', + ]); +}); + +it('throws the API error when the moderator was removed', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['message' => 'Not Found.'], 404]]); + + app(Client::class)->updateGuild('rust', 'Rust', 'Fearless.', 'πŸ¦€', removeIcon: false); +})->throws(ApiException::class); + +it('throws the API error when an edit with an icon is refused', function () { + fakeApi(['POST /api/v1/guilds/rust' => [['message' => 'The images.0 field must not be greater than 2048 kilobytes.', 'errors' => ['images.0' => ['The images.0 field must not be greater than 2048 kilobytes.']]], 422]]); + + app(Client::class)->updateGuild('rust', 'Rust', 'Fearless.', 'πŸ¦€', removeIcon: false, icon: new DraftImage(testPhoto(), 'image/png', 40, 30)); +})->throws(ApiException::class); diff --git a/tests/Feature/Screens/GuildBoardPinTest.php b/tests/Feature/Screens/GuildBoardPinTest.php new file mode 100644 index 00000000..4d345277 --- /dev/null +++ b/tests/Feature/Screens/GuildBoardPinTest.php @@ -0,0 +1,133 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * #rust's board, c1 pinned on top of c1, c2 and c3, as its moderator or not. + * devnull remembers a pin it took, so the board asked for again after it + * shows the new one, and refuses a pin with $refusal when one is given. + * + * @param array{0: mixed, 1: int}|null $refusal + */ +function rustBoard(bool $moderating = true, ?array $refusal = null): TestableComponent +{ + $pinned = 'c1'; + + serveApi(function (Request $request) use (&$pinned, $moderating, $refusal) { + $path = parse_url($request->url(), PHP_URL_PATH); + + if ($request->method() === 'GET' && $path === '/api/v1/guilds/rust') { + return Http::response(boardOf(['c1', 'c2', 'c3'], overrides: ['pinned_commit' => $pinned === null ? null : commitJson(['id' => $pinned]), 'can_moderate' => $moderating])); + } + + if (preg_match('#^/api/v1/guilds/rust/commits/(?[^/]+)/pin$#', (string) $path, $matches) === 1) { + if ($refusal !== null) { + return Http::response($refusal[0], $refusal[1]); + } + + $pinned = $request->method() === 'PUT' ? $matches['id'] : null; + + return Http::response(null, 204); + } + + return Http::response(['message' => 'No fake.'], 404); + }); + + return finishRefreshes(Native::visit('/log/guilds/rust', platform: 'android')); +} + +/** + * The menu item ids a commit's More holds. + * + * @return list + */ +function moreIds(TestableComponent $screen, string $id): array +{ + return array_values(array_filter(array_map(fn (array|string $item): ?string => is_array($item) ? $item[0] : null, menuItems($screen, 'more-'.$id)))); +} + +/** + * The ids of the commits the board draws below its pinned one, in order. + * + * @return list + */ +function boardRowIds(TestableComponent $screen): array +{ + $guild = $screen->instance(); + $commits = array_values(array_filter($guild->commits, fn ($commit): bool => $commit->id !== $guild->pinnedId)); + + return array_values(array_map(fn (TimelineRow $row): string => $row->commit->id, array_filter(Timeline::feed($commits), fn (TimelineRow $row): bool => ! $row->isDayMarker()))); +} + +it('offers the moderator Pin to board, and Unpin from board on the pinned commit', function () { + $screen = rustBoard(); + + expect(menuItems($screen, 'more-c2'))->toContain(['board-pin-c2', 'Pin to board', 'custom:pin']) + ->and(menuItems($screen, 'more-c1'))->toContain(['board-pin-c1', 'Unpin from board', 'custom:pin-off']); +}); + +it('offers no board pin to anyone but the moderator', function () { + $screen = rustBoard(moderating: false); + + expect(moreIds($screen, 'c2'))->not->toContain('board-pin-c2') + ->and(moreIds($screen, 'c1'))->not->toContain('board-pin-c1'); +}); + +it('offers no board pin outside the guild page', function () { + serveApi(fn () => Http::response(pageJson([commitJson(['id' => 'c2'])]))); + + expect(moreIds(Native::visit('/log', platform: 'android'), 'c2'))->not->toContain('board-pin-c2'); +}); + +it('pins a commit to the board and puts the old pin back on it', function () { + $screen = rustBoard(); + + $screen->tap('board-pin-c2') + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Commit pinned to the board.') + ->assertSet('pinnedId', 'c2'); + + expect(sentTo('PUT', 'guilds/rust/commits/c2/pin'))->toHaveCount(1) + ->and(boardRowIds($screen))->toBe(['c1', 'c3']) + ->and(menuItems($screen, 'more-c2'))->toContain(['board-pin-c2', 'Unpin from board', 'custom:pin-off']) + ->and(menuItems($screen, 'more-c1'))->toContain(['board-pin-c1', 'Pin to board', 'custom:pin']); +}); + +it('unpins the pinned commit back onto the board', function () { + $screen = rustBoard(); + + $screen->tap('board-pin-c1') + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Commit unpinned.') + ->assertSet('pinnedId', null); + + expect(boardRowIds($screen))->toBe(['c1', 'c2', 'c3']); +}); + +it('leaves the board as it was when devnull refuses the pin', function () { + $screen = rustBoard(refusal: [['message' => 'Not Found.'], 404]); + + $screen->tap('board-pin-c2')->assertSet('pinnedId', 'c1'); + + expect(boardRowIds($screen))->toBe(['c2', 'c3']); +}); + +it('asks for the board again after a pin, even while an earlier ask is still out', function () { + $screen = rustBoard(); + holdRefreshes(); + + $screen->call('load'); + $before = count($screen->bridge()->callsTo('AsyncTask.Dispatch')); + + $screen->tap('board-pin-c2'); + + expect(count($screen->bridge()->callsTo('AsyncTask.Dispatch')))->toBe($before + 1); +}); diff --git a/tests/Feature/Screens/GuildFormTest.php b/tests/Feature/Screens/GuildFormTest.php new file mode 100644 index 00000000..0a8d16d6 --- /dev/null +++ b/tests/Feature/Screens/GuildFormTest.php @@ -0,0 +1,289 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * The directory's first page, with one guild on it. + * + * @return array + */ +function directoryWithOneGuild(): array +{ + return ['data' => [guildJson()], 'links' => ['next' => null], 'meta' => ['current_page' => 1]]; +} + +/** + * The guild writes devnull was sent, as "METHOD path". + * + * @return list + */ +function guildWritesSent(): array +{ + return Http::recorded() + ->map(fn (array $pair): Request => $pair[0]) + ->filter(fn (Request $request): bool => $request->method() !== 'GET') + ->map(fn (Request $request): string => $request->method().' '.parse_url($request->url(), PHP_URL_PATH)) + ->values() + ->all(); +} + +/** + * A photo bigger than devnull takes for a guild icon, still a real PNG. + */ +function oversizedPhoto(): string +{ + $path = testPhoto(); + file_put_contents($path, str_repeat("\0", GuildForm::IconMaxBytes + 1), FILE_APPEND); + + return $path; +} + +it('offers Create a guild under the directory intro', function () { + fakeApi(['GET /api/v1/guilds' => [directoryWithOneGuild()]]); + + finishRefreshes(Native::visit('/guilds')) + ->assertSee('Start a public group.') + ->tap('create-guild') + ->assertNavigatedTo('/guilds/guilds/_new'); +}); + +it('hides Create a guild when guilds are unavailable', function () { + fakeApi(['GET /api/v1/guilds' => [['message' => 'Not Found'], 404]]); + + finishRefreshes(Native::visit('/guilds'))->assertDontSee('Start a public group.'); +}); + +it('shows the hashtag the name makes', function () { + Native::visit('/guilds/guilds/_new') + ->assertNavTitle('Create a guild') + ->assertSee('Your hashtag appears here') + ->set('name', 'Rust Lang!') + ->assertSee('#rustlang'); +}); + +it('refuses a name whose hashtag does not start with a letter', function () { + fakeApi([]); + + Native::visit('/guilds/guilds/_new') + ->set('name', 'πŸ¦€ 123') + ->set('description', 'Crabs.') + ->call('save') + ->assertSet('formError', 'Use a name whose hashtag starts with a letter.'); + + expect(guildWritesSent())->toBe([]); +}); + +it('refuses a name over 60 characters', function () { + fakeApi([]); + + Native::visit('/guilds/guilds/_new') + ->set('name', str_repeat('a', 61)) + ->set('description', 'Long.') + ->call('save') + ->assertSet('formError', 'The name must not be greater than 60 characters.'); + + expect(guildWritesSent())->toBe([]); +}); + +it('creates the guild and opens it in the form’s place', function () { + fakeApi(['POST /api/v1/guilds' => [['data' => guildJson(['handle' => 'rustlang'])], 201]]); + + Native::visit('/guilds/guilds/_new') + ->set('name', 'Rust Lang') + ->set('description', 'All about Rust.') + ->tap('save-guild') + ->assertReplacedWith('/guilds/guilds/rustlang'); + + expect(json_decode(sentTo('POST', 'guilds')[0], true))->toBe(['name' => 'Rust Lang', 'description' => 'All about Rust.', 'emoji' => 'πŸ’»']); +}); + +it('toasts and closes when the guild waits for review', function () { + fakeApi(['POST /api/v1/guilds' => [['message' => 'Your guild is waiting for review. It goes live once an admin approves it.'], 202]]); + + Native::visit('/guilds/guilds/_new') + ->set('name', 'Rust') + ->set('description', 'All about Rust.') + ->tap('save-guild') + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Your guild is waiting for review. It goes live once an admin approves it.') + ->assertWentBack(); +}); + +it("shows devnull's reason beside Create guild, and keeps what you wrote", function () { + $reason = 'A guild already uses this hashtag. Choose a different display name.'; + fakeApi(['POST /api/v1/guilds' => [['message' => $reason, 'errors' => ['handle' => [$reason]]], 422]]); + + Native::visit('/guilds/guilds/_new') + ->set('name', 'Rust') + ->set('description', 'All about Rust.') + ->tap('save-guild') + ->assertSet('formError', $reason) + ->assertSet('saving', false) + ->assertSet('name', 'Rust') + ->assertSee($reason) + ->assertNoNavigation(); +}); + +it('sends once while a save is in flight', function () { + fakeApi([]); + + Native::visit('/guilds/guilds/_new') + ->set('name', 'Rust') + ->set('description', 'All about Rust.') + ->set('saving', true) + ->call('save'); + + expect(guildWritesSent())->toBe([]); +}); + +it('refuses a picked image over 2 MB', function () { + $path = oversizedPhoto(); + + photosPicked(Native::visit('/guilds/guilds/_new'), [$path]) + ->assertSet('formError', 'Choose an image up to 2 MB.') + ->assertSet('icon', null); + + expect(file_exists($path))->toBeFalse(); +}); + +it('keeps a picked image and sends it as the icon', function () { + fakeApi(['POST /api/v1/guilds' => [['data' => guildJson()], 201]]); + + $screen = photosPicked(Native::visit('/guilds/guilds/_new'), [testPhoto()]); + + expect($screen->instance()->icon)->not->toBeNull(); + + $screen->set('name', 'Rust')->set('description', 'All about Rust.')->tap('save-guild'); + + expect(array_column(multipartParts(Http::recorded()[0][0]), 'name'))->toBe(['payload', 'images[]']); +}); + +it('takes an emoji devnull knows from the picker', function () { + Native::visit('/guilds/guilds/_new') + ->call('openEmojiPicker') + ->assertSet('emojiPickerOpen', true) + ->call('emojiPicked', 'πŸ¦€') + ->assertSet('emoji', 'πŸ¦€') + ->assertSet('emojiPickerOpen', false); +}); + +it('refuses an emoji devnull does not take', function () { + Native::visit('/guilds/guilds/_new') + ->call('emojiPicked', '🫟') + ->assertSet('emoji', GuildForm::DefaultEmoji) + ->assertSet('formError', 'Choose another emoji.'); +}); + +/** + * The guild form for editing #rust, opened from its page with what it shows. + * + * @param array $data + */ +function editRust(array $data = []): TestableComponent +{ + return Native::visit('/guilds/guilds/rust/edit', [ + 'name' => 'Rust', + 'description' => 'All about Rust.', + 'emoji' => 'πŸ¦€', + 'iconUrl' => null, + ...$data, + ]); +} + +it('opens filled in from the guild, with its hashtag fixed', function () { + editRust() + ->assertNavTitle('Edit guild') + ->assertSet('name', 'Rust') + ->assertSet('description', 'All about Rust.') + ->assertSet('emoji', 'πŸ¦€') + ->assertSee('#rust') + ->assertSee('As the moderator, you can change the display name, icon and description.') + ->assertSee('Save changes'); +}); + +it('refuses a name that changes the hashtag', function () { + fakeApi([]); + + editRust() + ->set('name', 'Go') + ->call('save') + ->assertSet('formError', "Guild display name doesn't match hashtag"); + + expect(guildWritesSent())->toBe([]); +}); + +it('saves changes and goes back to the guild', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['data' => guildJson(['name' => 'RUST'])]]]); + + editRust() + ->set('name', 'RUST') + ->tap('save-guild') + ->assertWentBack(); + + expect(json_decode(sentTo('PUT', 'guilds/rust')[0], true))->toBe(['name' => 'RUST', 'description' => 'All about Rust.', 'emoji' => 'πŸ¦€', 'remove_icon' => false]); +}); + +it('removes the uploaded icon when an emoji is chosen after an image', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['data' => guildJson()]]]); + $path = testPhoto(); + + $screen = photosPicked(editRust(['iconUrl' => 'http://devnull.test/api/v1/guilds/rust/icon']), [$path]); + $kept = $screen->instance()->icon->path; + + $screen->call('emojiPicked', 'πŸ¦€') + ->assertSet('icon', null) + ->assertSet('removeIcon', true) + ->tap('save-guild'); + + expect(file_exists($kept))->toBeFalse() + ->and(json_decode(sentTo('PUT', 'guilds/rust')[0], true))->toBe(['name' => 'Rust', 'description' => 'All about Rust.', 'emoji' => 'πŸ¦€', 'remove_icon' => true]); +}); + +it('says changes wait for review', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['message' => 'Your changes are waiting for review. They go live once an admin approves them.'], 202]]); + + editRust() + ->tap('save-guild') + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Your changes are waiting for review. They go live once an admin approves them.') + ->assertWentBack(); +}); + +it('goes back to the guild when devnull says you no longer moderate it', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['message' => 'Not Found.'], 404]]); + + editRust() + ->tap('save-guild') + ->assertNativeCalled('ToastKit.Show') + ->assertWentBack(); +}); + +it('keeps the form when devnull refuses the fields', function () { + fakeApi(['PUT /api/v1/guilds/rust' => [['message' => 'The description field is required.', 'errors' => ['description' => ['The description field is required.']]], 422]]); + + editRust() + ->tap('save-guild') + ->assertSet('formError', 'The description field is required.') + ->assertSet('saving', false) + ->assertNoNavigation(); +}); + +it('says nothing when the photo picker is cancelled', function () { + photosPicked(Native::visit('/guilds/guilds/_new'), []) + ->assertSet('formError', null) + ->assertSet('icon', null); +}); + +it('opens a guild whose hashtag is #new as that guild, not the form', function () { + fakeApi(['GET /api/v1/guilds/new' => [boardOf(['c1'], overrides: ['guild' => guildJson(['handle' => 'new', 'name' => 'New'])])]]); + + expect(Native::visit('/log/guilds/new')->instance())->toBeInstanceOf(Guild::class); +}); diff --git a/tests/Feature/Screens/GuildMenuTest.php b/tests/Feature/Screens/GuildMenuTest.php index 258ab43d..9dce0416 100644 --- a/tests/Feature/Screens/GuildMenuTest.php +++ b/tests/Feature/Screens/GuildMenuTest.php @@ -301,3 +301,18 @@ function guildSent(string $method, string $path): bool expect(nodeByRef($screen, 'guild-report-sheet')['props']['visible'] ?? false)->toBeFalse() ->and($screen->instance()->guildReportOpen)->toBeFalse(); }); + +it('shows the moderator Edit in the guild header, which opens the guild form', function () { + fakeApi(['GET /api/v1/guilds/rust' => [boardOf(['c1'], overrides: ['can_moderate' => true, 'guild' => guildJson(['is_joined' => true])])]]); + + finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('Edit') + ->tap('guild-edit') + ->assertNavigatedTo('/log/guilds/rust/edit', ['name' => 'Rust', 'description' => 'All about rust.', 'emoji' => 'πŸ’»', 'iconUrl' => null]); +}); + +it('leaves Edit out of the header for everyone else', function () { + fakeApi(['GET /api/v1/guilds/rust' => [boardOf(['c1'], overrides: ['guild' => guildJson(['is_joined' => true])])]]); + + expect(findNode(finishRefreshes(Native::visit('/log/guilds/rust'))->tree(), fn (array $node): bool => ($node['props']['ref'] ?? $node['ref'] ?? null) === 'guild-edit'))->toBeNull(); +}); diff --git a/tests/Feature/Screens/GuildsTest.php b/tests/Feature/Screens/GuildsTest.php index e7e18c2f..f6d3f6c8 100644 --- a/tests/Feature/Screens/GuildsTest.php +++ b/tests/Feature/Screens/GuildsTest.php @@ -279,3 +279,13 @@ function serveGuilds(array $pages): void expect(app(Account::class)->guildsTabShown())->toBeFalse(); }); + +it('marks the guilds you have joined at the end of their row', function () { + serveApi(['GET /api/v1/guilds' => [guildsPage([guildJson(['handle' => 'rust', 'is_joined' => true]), guildJson(['handle' => 'go'])])]]); + + $screen = finishRefreshes(Native::visit('/guilds')); + + expect(nodeByRef($screen, 'guild-rust')['props']['a11y_label'] ?? nodeByRef($screen, 'guild-rust')['a11y_label'] ?? null)->toBe('Rust, #rust, 3 members, joined') + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'guild-joined-rust'))->not->toBeNull() + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'guild-joined-go'))->toBeNull(); +});