diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 4cf327f29..33fc496bc 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -620,6 +620,7 @@ A signed request sees what the web shows you, such as your own pending commits a - pin a commit to your profile, or unpin it; - translate commits; - suggest people to mention and /dev/null issues to reference while writing; +- suggest up to six guilds by handle or name while typing a hashtag, as the composer does, while guilds are available to you; - sync from GitHub, save your lane color, timezone, and translation language, and turn automatic translation on or off; - list your devices and revoke them; - delete your account. diff --git a/app/Http/Controllers/Api/GuildSuggestionController.php b/app/Http/Controllers/Api/GuildSuggestionController.php new file mode 100644 index 000000000..a1dd96149 --- /dev/null +++ b/app/Http/Controllers/Api/GuildSuggestionController.php @@ -0,0 +1,24 @@ +suggestions($request->term())) + ->response() + ->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Requests/ListApiGuildSuggestionsRequest.php b/app/Http/Requests/ListApiGuildSuggestionsRequest.php new file mode 100644 index 000000000..29502e53a --- /dev/null +++ b/app/Http/Requests/ListApiGuildSuggestionsRequest.php @@ -0,0 +1,34 @@ +available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array> */ + public function rules(): array + { + return [ + 'q' => ['nullable', 'string', 'max:100'], + ]; + } + + /** + * What follows the hashtag, so an app can send the word it is completing with or without its #. + */ + public function term(): string + { + return $this->string('q')->trim()->ltrim('#')->trim()->lower()->value(); + } +} diff --git a/app/Queries/GuildsQuery.php b/app/Queries/GuildsQuery.php index 8d220ff1c..4ce497977 100644 --- a/app/Queries/GuildsQuery.php +++ b/app/Queries/GuildsQuery.php @@ -62,15 +62,30 @@ public function references(array $handles): Collection public function suggestions(string $term): Collection { $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term); + $handle = $this->folded('handle'); + $name = $this->folded('name'); + $search = $this->folded('?'); return Guild::query()->select(['handle', 'name', 'emoji', 'icon_path', 'updated_at'])->withCount('members') ->where(fn (Builder $query): Builder => $query - ->whereRaw('TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]) - ->orWhereRaw('TRANSLATE(LOWER(name COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"])) - ->orderByRaw('CASE WHEN TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\' THEN 0 ELSE 1 END', ["{$escaped}%"]) + ->whereRaw("{$handle} LIKE {$search} ESCAPE '!'", ["%{$escaped}%"]) + ->orWhereRaw("{$name} LIKE {$search} ESCAPE '!'", ["%{$escaped}%"])) + ->orderByRaw("CASE WHEN {$handle} LIKE {$search} ESCAPE '!' THEN 0 ELSE 1 END", ["{$escaped}%"]) ->orderByDesc('members_count')->orderBy('handle')->limit(6)->get(); } + /** + * Lowercases for matching, folding the final sigma into σ and dropping the combining dot above: handles are + * lowercased in PHP, which turns İ into i and that dot, while the database turns İ into a plain i. + * + * @param literal-string $operand + * @return literal-string + */ + private function folded(string $operand): string + { + return "TRANSLATE(LOWER({$operand} COLLATE \"pg_c_utf8\"), 'ς\u{0307}', 'σ')"; + } + /** * The member count and whether the user joined or muted each guild come from one read, so they always agree. * diff --git a/routes/api.php b/routes/api.php index ee64eceef..821a9e381 100644 --- a/routes/api.php +++ b/routes/api.php @@ -38,6 +38,7 @@ use App\Http\Controllers\Api\GuildMuteController; use App\Http\Controllers\Api\GuildReadController; use App\Http\Controllers\Api\GuildReportController; +use App\Http\Controllers\Api\GuildSuggestionController; use App\Http\Controllers\Api\HeadlineController; use App\Http\Controllers\Api\IssueController; use App\Http\Controllers\Api\IssueSuggestionController; @@ -273,10 +274,13 @@ ->middleware('throttle:120,1,guild-reads:') ->name('api-guild-read.update'); - // Composer suggestions: people to mention and /dev/null issues to reference, as the web's composer suggests them... + // Composer suggestions: people to mention, guilds to tag and /dev/null issues to reference, as the web's composer suggests them... Route::get('search/mentions', [MentionSuggestionController::class, 'index']) ->middleware('throttle:people') ->name('api-mention-suggestion.index'); + Route::get('search/guilds', [GuildSuggestionController::class, 'index']) + ->middleware('throttle:people') + ->name('api-guild-suggestion.index'); Route::get('search/issues', [IssueSuggestionController::class, 'index']) ->middleware('throttle:issue-suggestions') ->name('api-issue-suggestion.index'); diff --git a/tests/Feature/Controllers/Api/GuildSuggestionControllerTest.php b/tests/Feature/Controllers/Api/GuildSuggestionControllerTest.php new file mode 100644 index 000000000..03459d4ad --- /dev/null +++ b/tests/Feature/Controllers/Api/GuildSuggestionControllerTest.php @@ -0,0 +1,148 @@ +update(Feature::Guilds, true, adminOnly: false); + + $this->user = User::factory()->create(); + $this->keyPair = apiKeyPairFor($this->user); +}); + +it('suggests six guilds with handle prefixes before popular name matches, as the web composer does', function (): void { + Guild::factory()->count(7)->sequence(fn ($sequence): array => [ + 'handle' => 'group0'.$sequence->index, + 'name' => 'Rust developers', + 'emoji' => '🦀', + 'icon_path' => null, + ])->create(); + Guild::query()->where('handle', 'group06')->firstOrFail()->members()->attach($this->user, ['joined_at' => now()]); + Guild::factory()->create(['handle' => 'rustaceans', 'name' => 'Systems', 'emoji' => '🦀', 'icon_path' => null]); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'RUST'])) + ->assertOk() + ->assertHeader('Cache-Control', 'no-store, private') + ->assertExactJson(['data' => collect(['rustaceans', 'group06', 'group00', 'group01', 'group02', 'group03']) + ->map(fn (string $handle): array => [ + 'handle' => $handle, + 'name' => $handle === 'rustaceans' ? 'Systems' : 'Rust developers', + 'emoji' => '🦀', + 'icon_url' => null, + ])->all()]); +}); + +it('ignores a leading hashtag and surrounding spaces', function (string $query): void { + Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans']); + Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $query])) + ->assertOk() + ->assertJsonPath('data.*.handle', ['laravel']); +})->with(['#lara', ' #LARA ', '# lara', '##lara']); + +it('matches display names as well as handles', function (): void { + Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans']); + Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'ARTISANS'])) + ->assertOk() + ->assertJsonPath('data.*.handle', ['laravel']); +}); + +it('suggests the six most popular guilds for a bare hashtag', function (?string $query): void { + Guild::factory()->count(7)->sequence(fn ($sequence): array => ['handle' => 'guild'.$sequence->index])->create(); + $rust = Guild::factory()->create(['handle' => 'rust']); + $rust->members()->attach($this->user, ['joined_at' => now()]); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', array_filter(['q' => $query]))) + ->assertOk() + ->assertJsonPath('data.*.handle', ['rust', 'guild0', 'guild1', 'guild2', 'guild3', 'guild4']); +})->with([null, '#']); + +it('still suggests paused guilds and guilds the user muted, as the web composer does', function (): void { + Guild::factory()->create(['handle' => 'rustpaused', 'user_id' => null]); + Guild::factory()->create(['handle' => 'rustmuted'])->muters()->attach($this->user, ['muted_at' => now()]); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust'])) + ->assertOk() + ->assertJsonPath('data.*.handle', ['rustmuted', 'rustpaused']); +}); + +it('gives icons the API signs for the user, without private guild fields', function (): void { + $rust = Guild::factory()->create(['handle' => 'rust', 'name' => 'Rust', 'description' => 'Fearless', 'emoji' => '🦀', 'icon_path' => 'guild-icons/rust.webp']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust'])) + ->assertOk() + ->assertExactJson(['data' => [[ + 'handle' => 'rust', + 'name' => 'Rust', + 'emoji' => '🦀', + 'icon_url' => $rust->apiIconUrl($this->user), + ]]]); +}); + +it('matches literal wildcards and Unicode names', function (string $term, string $name): void { + Guild::factory()->create(['handle' => 'match', 'name' => $name]); + Guild::factory()->create(['handle' => 'other', 'name' => 'Other']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $term])) + ->assertOk() + ->assertJsonPath('data.*.handle', ['match']); +})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ'], ['İstanbul', 'İstanbul'], ['istanbul', 'İSTANBUL']]); + +it('matches a handle with a dotted capital I however it is typed', function (string $term): void { + Guild::factory()->create(['handle' => mb_strtolower('İstanbul'), 'name' => 'City']); + Guild::factory()->create(['handle' => 'other', 'name' => 'Other']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $term])) + ->assertOk() + ->assertJsonPath('data.*.handle', [mb_strtolower('İstanbul')]); +})->with(['İstanbul', 'istanbul', 'İst']); + +it('suggests no guilds while guilds are not available to the user', function (bool $enabled, bool $adminOnly): void { + resolve(Features::class)->update(Feature::Guilds, $enabled, $adminOnly); + Guild::factory()->create(['handle' => 'rust']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))->assertNotFound(); +})->with([ + 'admin preview' => [true, true], + 'switched off' => [false, false], +]); + +it('suggests guilds to admins during the admin preview', function (): void { + config(['app.admins' => [$this->user->handle]]); + resolve(Features::class)->update(Feature::Guilds, true, adminOnly: true); + Guild::factory()->create(['handle' => 'rust']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust'])) + ->assertOk() + ->assertJsonPath('data.*.handle', ['rust']); +}); + +it('rejects an invalid search', function (mixed $query): void { + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $query])) + ->assertUnprocessable() + ->assertJsonValidationErrors('q'); +})->with([ + 'array' => [['rust']], + 'too long' => [str_repeat('x', 101)], +]); + +it('shares the 120 people lookups a minute with the web', function (): void { + foreach (range(1, 120) as $lookup) { + $this->actingAs($this->user)->getJson(route('guild-suggestions.index', ['q' => 'rust']))->assertOk(); + } + + signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust'])) + ->assertTooManyRequests() + ->assertExactJson(['message' => 'Too Many Attempts.', 'code' => 'rate_limited']); +}); + +it('requires a signed request', function (): void { + $this->getJson(route('api-guild-suggestion.index', ['q' => 'rust']))->assertUnauthorized(); +}); diff --git a/tests/Feature/Controllers/GuildSuggestionControllerTest.php b/tests/Feature/Controllers/GuildSuggestionControllerTest.php index 053aa996c..dc16014a6 100644 --- a/tests/Feature/Controllers/GuildSuggestionControllerTest.php +++ b/tests/Feature/Controllers/GuildSuggestionControllerTest.php @@ -48,7 +48,16 @@ $this->actingAs(User::factory()->create(['handle' => 'admin'])) ->getJson(route('guild-suggestions.index', ['q' => $term])) ->assertOk()->assertJsonCount(1, 'guilds')->assertJsonPath('guilds.0.handle', 'match'); -})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ']]); +})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ'], ['i̇stanbul', 'İstanbul'], ['istanbul', 'İSTANBUL']]); + +it('matches a handle with a dotted capital I however it is typed', function (string $term): void { + Guild::factory()->create(['handle' => mb_strtolower('İstanbul'), 'name' => 'City']); + Guild::factory()->create(['handle' => 'other', 'name' => 'Other']); + + $this->actingAs(User::factory()->create(['handle' => 'admin'])) + ->getJson(route('guild-suggestions.index', ['q' => $term])) + ->assertOk()->assertJsonCount(1, 'guilds')->assertJsonPath('guilds.0.handle', mb_strtolower('İstanbul')); +})->with(['i̇stanbul', 'istanbul', 'i̇st']); it('protects suggestions behind sign in and guild feature access', function (): void { $this->getJson(route('guild-suggestions.index'))->assertUnauthorized();