diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 3f5edb7f11..8833629a93 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -583,6 +583,7 @@ A signed request sees what the web shows you, such as your own pending commits a - commit, reply, and quote, with images, and delete your commits, with the same undo window as the web; - preview commit drafts without publishing them; - follow or unfollow people and organizations, mute or unmute, and block or unblock, and list who you muted and blocked; +- list a developer's followers, the people they follow, their mutuals, and the followers you know, with the profiles each bio mentions linked as on their profile; - read who to follow, also as it is suggested beside a profile or a commit, and mark a suggestion not interested; - star or unstar, and list who starred your own commit, newest first, 20 a page; - create polls on commits that are neither replies nor quotes, and vote on polls; diff --git a/app/Http/Controllers/Api/UserFollowersController.php b/app/Http/Controllers/Api/UserFollowersController.php index d9b298e874..5e4c1bd9f2 100644 --- a/app/Http/Controllers/Api/UserFollowersController.php +++ b/app/Http/Controllers/Api/UserFollowersController.php @@ -5,20 +5,22 @@ namespace App\Http\Controllers\Api; use App\Http\Requests\ListApiUserFollowersRequest; -use App\Http\Resources\UserResource; +use App\Http\Resources\UserConnectionCollection; use App\Models\User; +use App\Queries\BioProfilesQuery; use App\Queries\UserConnectionsQuery; use Illuminate\Container\Attributes\CurrentUser; -use Illuminate\Http\Resources\Json\AnonymousResourceCollection; final readonly class UserFollowersController { /** - * The people following a user, 30 a page as on the web, with whether the signed-in user follows each one, and whether - * each one follows them. + * The people following a user, 30 a page as on the web, with whether the signed-in user follows each one, whether each + * one follows them, and the profiles each one's bio mentions. */ - public function index(ListApiUserFollowersRequest $request, #[CurrentUser] User $currentUser, User $user, UserConnectionsQuery $connections): AnonymousResourceCollection + public function index(ListApiUserFollowersRequest $request, #[CurrentUser] User $currentUser, User $user, UserConnectionsQuery $connections, BioProfilesQuery $bioProfiles): UserConnectionCollection { - return UserResource::collection($connections->builder($user->followers(), $currentUser)->cursorPaginate(30)); + $page = $connections->builder($user->followers(), $currentUser)->cursorPaginate(30); + + return new UserConnectionCollection($page, $bioProfiles->getMany($page->items())); } } diff --git a/app/Http/Controllers/Api/UserFollowersYouKnowController.php b/app/Http/Controllers/Api/UserFollowersYouKnowController.php new file mode 100644 index 0000000000..3222320679 --- /dev/null +++ b/app/Http/Controllers/Api/UserFollowersYouKnowController.php @@ -0,0 +1,27 @@ +builder($followersYouKnow->builder($user, $currentUser), $currentUser)->cursorPaginate(30); + + return new UserConnectionCollection($page, $bioProfiles->getMany($page->items())); + } +} diff --git a/app/Http/Controllers/Api/UserFollowingController.php b/app/Http/Controllers/Api/UserFollowingController.php index 8fe557f287..d68c25bf19 100644 --- a/app/Http/Controllers/Api/UserFollowingController.php +++ b/app/Http/Controllers/Api/UserFollowingController.php @@ -5,20 +5,22 @@ namespace App\Http\Controllers\Api; use App\Http\Requests\ListApiUserFollowingRequest; -use App\Http\Resources\UserResource; +use App\Http\Resources\UserConnectionCollection; use App\Models\User; +use App\Queries\BioProfilesQuery; use App\Queries\UserConnectionsQuery; use Illuminate\Container\Attributes\CurrentUser; -use Illuminate\Http\Resources\Json\AnonymousResourceCollection; final readonly class UserFollowingController { /** - * The people a user follows, 30 a page as on the web, with whether the signed-in user follows each one, and whether - * each one follows them. + * The people a user follows, 30 a page as on the web, with whether the signed-in user follows each one, whether each + * one follows them, and the profiles each one's bio mentions. */ - public function index(ListApiUserFollowingRequest $request, #[CurrentUser] User $currentUser, User $user, UserConnectionsQuery $connections): AnonymousResourceCollection + public function index(ListApiUserFollowingRequest $request, #[CurrentUser] User $currentUser, User $user, UserConnectionsQuery $connections, BioProfilesQuery $bioProfiles): UserConnectionCollection { - return UserResource::collection($connections->builder($user->following(), $currentUser)->cursorPaginate(30)); + $page = $connections->builder($user->following(), $currentUser)->cursorPaginate(30); + + return new UserConnectionCollection($page, $bioProfiles->getMany($page->items())); } } diff --git a/app/Http/Controllers/Api/UserMutualsController.php b/app/Http/Controllers/Api/UserMutualsController.php new file mode 100644 index 0000000000..d6acf94bcb --- /dev/null +++ b/app/Http/Controllers/Api/UserMutualsController.php @@ -0,0 +1,26 @@ +builder($connections->mutuals($user), $currentUser)->cursorPaginate(30); + + return new UserConnectionCollection($page, $bioProfiles->getMany($page->items())); + } +} diff --git a/app/Http/Controllers/UserFollowersYouKnowController.php b/app/Http/Controllers/UserFollowersYouKnowController.php index f4f11f83ef..494936b0a6 100644 --- a/app/Http/Controllers/UserFollowersYouKnowController.php +++ b/app/Http/Controllers/UserFollowersYouKnowController.php @@ -10,7 +10,6 @@ use App\Queries\FollowersYouKnowQuery; use App\Queries\UserConnectionsQuery; use Illuminate\Container\Attributes\CurrentUser; -use Illuminate\Database\Eloquent\Builder; use Inertia\Inertia; use Inertia\Response; @@ -21,13 +20,8 @@ public function index(ListUserFollowersYouKnowRequest $request, #[CurrentUser] U return Inertia::render('user/connections', [ 'user' => $user, 'type' => ConnectionType::FollowersYouKnow, - 'loadedDigest' => Inertia::optional(fn (): array => ['users' => $connections->loadedDigest($followersYouKnow->builder($user, $currentUser), $request->loaded('users'))]), - 'users' => Inertia::scroll(fn () => $followersYouKnow->builder($user, $currentUser) - ->withExists([ - 'followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($currentUser->id), - 'following as follows_you' => fn (Builder $query): Builder => $query->whereKey($currentUser->id), - ]) - ->cursorPaginate(30)), + 'loadedDigest' => Inertia::optional(fn (): array => ['users' => $connections->loadedDigest($connections->builder($followersYouKnow->builder($user, $currentUser), $currentUser), $request->loaded('users'))]), + 'users' => Inertia::scroll(fn () => $connections->builder($followersYouKnow->builder($user, $currentUser), $currentUser)->cursorPaginate(30)), ]); } } diff --git a/app/Http/Controllers/UserMutualsController.php b/app/Http/Controllers/UserMutualsController.php index 87397e053e..987e3bc8d5 100644 --- a/app/Http/Controllers/UserMutualsController.php +++ b/app/Http/Controllers/UserMutualsController.php @@ -9,8 +9,6 @@ use App\Models\User; use App\Queries\UserConnectionsQuery; use Illuminate\Container\Attributes\CurrentUser; -use Illuminate\Database\Eloquent\Relations\BelongsToMany; -use Illuminate\Database\Query\Builder as QueryBuilder; use Inertia\Inertia; use Inertia\Response; @@ -24,19 +22,8 @@ public function index(ListUserMutualsRequest $request, #[CurrentUser] User $curr return Inertia::render('user/connections', [ 'user' => $user, 'type' => ConnectionType::Mutuals, - 'loadedDigest' => Inertia::optional(fn (): array => ['users' => $connections->loadedDigest($this->mutuals($user, $currentUser, $connections), $request->loaded('users'))]), - 'users' => Inertia::scroll(fn () => $this->mutuals($user, $currentUser, $connections)->cursorPaginate(30)), + 'loadedDigest' => Inertia::optional(fn (): array => ['users' => $connections->loadedDigest($connections->builder($connections->mutuals($user), $currentUser), $request->loaded('users'))]), + 'users' => Inertia::scroll(fn () => $connections->builder($connections->mutuals($user), $currentUser)->cursorPaginate(30)), ]); } - - /** - * @return BelongsToMany - */ - private function mutuals(User $user, User $viewer, UserConnectionsQuery $connections): BelongsToMany - { - return $connections->builder($user->following() - ->whereExists(fn (QueryBuilder $query): QueryBuilder => $query->from('follows', 'follows_back') - ->whereColumn('follows_back.follower_id', 'users.id') - ->where('follows_back.followed_id', $user->id)), $viewer); - } } diff --git a/app/Http/Requests/ListApiUserFollowersYouKnowRequest.php b/app/Http/Requests/ListApiUserFollowersYouKnowRequest.php new file mode 100644 index 0000000000..0daa5fe6d8 --- /dev/null +++ b/app/Http/Requests/ListApiUserFollowersYouKnowRequest.php @@ -0,0 +1,40 @@ +route('user'); + assert($user instanceof User); + + $viewer = $this->user(); + assert($viewer instanceof User); + + $blockerId = $viewer->blockerIdWith($user); + + throw_if($blockerId !== null, fn (): ApiException => ApiException::acrossBlock($user, blockedByViewer: $blockerId === $viewer->id, shown: UserResource::make($user))); + + return true; + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/ListApiUserMutualsRequest.php b/app/Http/Requests/ListApiUserMutualsRequest.php new file mode 100644 index 0000000000..015d1a368d --- /dev/null +++ b/app/Http/Requests/ListApiUserMutualsRequest.php @@ -0,0 +1,40 @@ +route('user'); + assert($user instanceof User); + + $viewer = $this->user(); + assert($viewer instanceof User); + + $blockerId = $viewer->blockerIdWith($user); + + throw_if($blockerId !== null, fn (): ApiException => ApiException::acrossBlock($user, blockedByViewer: $blockerId === $viewer->id, shown: UserResource::make($user))); + + return true; + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Resources/UserConnectionCollection.php b/app/Http/Resources/UserConnectionCollection.php new file mode 100644 index 0000000000..adc4cd3d4a --- /dev/null +++ b/app/Http/Resources/UserConnectionCollection.php @@ -0,0 +1,37 @@ + $page + * @param array> $bioProfiles + */ + public function __construct(private readonly CursorPaginator $page, private readonly array $bioProfiles) + { + parent::__construct($page); + } + + /** + * @return array> + */ + public function toArray(Request $request): array + { + return array_map(fn (User $user): array => [ + ...UserResource::make($user)->toArray($request), + 'bio_profiles' => (object) $this->bioProfiles[$user->id], + ], $this->page->items()); + } +} diff --git a/app/Queries/BioProfilesQuery.php b/app/Queries/BioProfilesQuery.php index 353c04e21d..4833845ab9 100644 --- a/app/Queries/BioProfilesQuery.php +++ b/app/Queries/BioProfilesQuery.php @@ -24,8 +24,37 @@ public function __construct(private Mentions $mentions) */ public function get(User $user): array { - $handles = $this->mentions->handles("{$user->bio}\n{$user->company}"); + return $this->profiles($this->handles($user)); + } + /** + * What get() returns for each user, by user id, with one query for the whole page. + * + * @param iterable $users + * @return array> + */ + public function getMany(iterable $users): array + { + $handles = collect($users)->mapWithKeys(fn (User $user): array => [$user->id => $this->handles($user)]); + $profiles = $this->profiles(array_values(array_unique(array_merge(...$handles->values()->all())))); + + return $handles->map(fn (array $mentioned): array => array_intersect_key($profiles, array_flip($mentioned)))->all(); + } + + /** + * @return list + */ + private function handles(User $user): array + { + return $this->mentions->handles("{$user->bio}\n{$user->company}"); + } + + /** + * @param list $handles + * @return array + */ + private function profiles(array $handles): array + { if ($handles === []) { return []; } diff --git a/app/Queries/FollowersYouKnowQuery.php b/app/Queries/FollowersYouKnowQuery.php index 5e76332c4f..f9af10c688 100644 --- a/app/Queries/FollowersYouKnowQuery.php +++ b/app/Queries/FollowersYouKnowQuery.php @@ -13,7 +13,7 @@ public const int PREVIEW_COUNT = 3; /** - * A user's followers whom the viewer follows too, as the web lists them: the newest follow of the user first. + * A user's followers whom the viewer follows too, for UserConnectionsQuery::builder() to order and flag. * * @return BelongsToMany */ @@ -22,9 +22,7 @@ public function builder(User $user, User $viewer): BelongsToMany $following = $viewer->following(); return $user->followers() - ->whereIn('users.id', $following->newPivotQuery()->select($following->getRelatedPivotKeyName())) - ->latest('follows.created_at') - ->latest('users.id'); + ->whereIn('users.id', $following->newPivotQuery()->select($following->getRelatedPivotKeyName())); } /** diff --git a/app/Queries/UserConnectionsQuery.php b/app/Queries/UserConnectionsQuery.php index 7b0a9d42c4..1c1d845bb1 100644 --- a/app/Queries/UserConnectionsQuery.php +++ b/app/Queries/UserConnectionsQuery.php @@ -8,11 +8,12 @@ use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Query\Builder as QueryBuilder; final readonly class UserConnectionsQuery { /** - * A user's followers, or the people they follow, as the web lists them: the newest follow first, with whether the + * Any of a user's connection lists, as the web lists them: the newest follow first, with whether the * viewer follows each one, and whether each one follows them. * * @param BelongsToMany $connections @@ -29,6 +30,19 @@ public function builder(BelongsToMany $connections, User $viewer): BelongsToMany ->latest('users.id'); } + /** + * The people a user follows who follow them back. + * + * @return BelongsToMany + */ + public function mutuals(User $user): BelongsToMany + { + return $user->following() + ->whereExists(fn (QueryBuilder $query): QueryBuilder => $query->from('follows', 'follows_back') + ->whereColumn('follows_back.follower_id', 'users.id') + ->where('follows_back.followed_id', $user->id)); + } + /** * Which of a list a page loaded, as a digest of the sorted ids of as many as it loaded from the start, so a page * that may have missed follows changing can tell whether its loaded pages still hold the same, even when as many diff --git a/routes/api.php b/routes/api.php index e90e010f25..8506050224 100644 --- a/routes/api.php +++ b/routes/api.php @@ -74,10 +74,12 @@ use App\Http\Controllers\Api\UserFollowController; use App\Http\Controllers\Api\UserFollowedOrganizationController; use App\Http\Controllers\Api\UserFollowersController; +use App\Http\Controllers\Api\UserFollowersYouKnowController; use App\Http\Controllers\Api\UserFollowingController; use App\Http\Controllers\Api\UserLaneController; use App\Http\Controllers\Api\UserLiveController; use App\Http\Controllers\Api\UserMuteController; +use App\Http\Controllers\Api\UserMutualsController; use App\Http\Controllers\Api\UserPasteisModeController; use App\Http\Controllers\Api\UserProfileController; use App\Http\Controllers\Api\UserPushPreferencesController; @@ -211,6 +213,10 @@ ->name('api-user-followers.index'); Route::get('users/{user:handle}/following', [UserFollowingController::class, 'index']) ->name('api-user-following.index'); + Route::get('users/{user:handle}/mutuals', [UserMutualsController::class, 'index']) + ->name('api-user-mutuals.index'); + Route::get('users/{user:handle}/followers-you-know', [UserFollowersYouKnowController::class, 'index']) + ->name('api-user-followers-you-know.index'); Route::get('users/{user:handle}/following/organizations', [UserFollowedOrganizationController::class, 'index']) ->name('api-user-followed-organization.index'); diff --git a/tests/Feature/Controllers/Api/UserFollowersControllerTest.php b/tests/Feature/Controllers/Api/UserFollowersControllerTest.php index 483f590d45..91ed103935 100644 --- a/tests/Feature/Controllers/Api/UserFollowersControllerTest.php +++ b/tests/Feature/Controllers/Api/UserFollowersControllerTest.php @@ -12,6 +12,21 @@ $this->getJson('/api/v1/users/octocat/followers')->assertUnauthorized(); }); +it("links the profiles each follower's bio mentions, as their profile does", function (): void { + $user = User::factory()->create(); + User::factory()->create(['handle' => 'TaylorOtwell']); + $linked = User::factory()->create(['bio' => 'Thanks @taylorotwell']); + $plain = User::factory()->create(['bio' => 'Ships on Fridays.', 'company' => null]); + $user->followers()->attach($linked, ['created_at' => now()->subMinute()]); + $user->followers()->attach($plain); + + $response = signedApiRequest(apiKeyPairFor(User::factory()->create()), 'GET', route('api-user-followers.index', $user)) + ->assertOk() + ->assertJsonPath('data.1.bio_profiles', ['taylorotwell' => 'TaylorOtwell']); + + expect(json_decode($response->getContent(), flags: JSON_THROW_ON_ERROR)->data[0]->bio_profiles)->toEqual(new stdClass()); +}); + it('lists the followers of a user, newest follow first', function (): void { $user = User::factory()->create(['handle' => 'octocat']); $earlier = User::factory()->create(['bio' => 'Ships on Fridays.']); @@ -101,10 +116,11 @@ // The first signed request also syncs the user's keys with GitHub... $queries(); - $user->followers()->attach(User::factory()->create()); + User::factory()->create(['handle' => 'taylorotwell']); + $user->followers()->attach(User::factory()->create(['bio' => 'Thanks @taylorotwell'])); $withOne = $queries(); - $user->followers()->attach(User::factory()->count(5)->create()); + $user->followers()->attach(User::factory()->count(5)->create(['bio' => 'Thanks @taylorotwell'])); expect($queries())->toBe($withOne); }); diff --git a/tests/Feature/Controllers/Api/UserFollowersYouKnowControllerTest.php b/tests/Feature/Controllers/Api/UserFollowersYouKnowControllerTest.php new file mode 100644 index 0000000000..ba85ecc1ad --- /dev/null +++ b/tests/Feature/Controllers/Api/UserFollowersYouKnowControllerTest.php @@ -0,0 +1,110 @@ +create(['handle' => 'octocat']); + + $this->getJson('/api/v1/users/octocat/followers-you-know')->assertUnauthorized(); +}); + +it('lists the followers of a user whom the signed-in user follows, newest follow first', function (): void { + $viewer = User::factory()->create(); + $user = User::factory()->create(); + User::factory()->create(['handle' => 'TaylorOtwell']); + $earlier = User::factory()->create(['bio' => 'Thanks @taylorotwell']); + $later = User::factory()->create(['bio' => 'Ships on Fridays.', 'company' => null]); + $user->followers()->attach($earlier, ['created_at' => now()->subMinute()]); + $user->followers()->attach($later); + $user->followers()->attach(User::factory()->create()); + $viewer->following()->attach([$earlier->id, $later->id, User::factory()->create()->id]); + $viewer->followers()->attach($later); + + $response = signedApiRequest(apiKeyPairFor($viewer), 'GET', route('api-user-followers-you-know.index', $user)) + ->assertOk() + ->assertJsonPath('data.*.id', [$later->id, $earlier->id]) + ->assertJsonPath('data.*.is_followed', [true, true]) + ->assertJsonPath('data.*.follows_you', [true, false]) + ->assertJsonPath('data.1.bio_profiles', ['taylorotwell' => 'TaylorOtwell']) + ->assertJsonMissingPath('data.0.email') + ->assertJsonPath('meta.next_cursor', null); + + expect(json_decode($response->getContent(), flags: JSON_THROW_ON_ERROR)->data[0]->bio_profiles)->toEqual(new stdClass()); +}); + +it('pages through the followers you know 30 at a time with a cursor, by id within the same moment', function (): void { + $this->freezeTime(); + $viewer = User::factory()->create(); + $keyPair = apiKeyPairFor($viewer); + $user = User::factory()->create(); + $known = User::factory()->count(31)->create(); + + foreach ($known as $follower) { + $user->followers()->attach($follower); + } + + $viewer->following()->attach($known); + + $first = signedApiRequest($keyPair, 'GET', route('api-user-followers-you-know.index', $user)) + ->assertOk() + ->assertJsonCount(30, 'data') + ->assertJsonPath('meta.per_page', 30); + + signedApiRequest($keyPair, 'GET', $first->json('links.next')) + ->assertOk() + ->assertJsonPath('data.*.id', [$known->sortByDesc('id')->last()->id]) + ->assertJsonPath('meta.next_cursor', null); +}); + +it('loads a page of the followers you know without a query per follower', function (): void { + $viewer = User::factory()->create(); + $keyPair = apiKeyPairFor($viewer); + $user = User::factory()->create(); + User::factory()->create(['handle' => 'taylorotwell']); + + $queries = function () use ($keyPair, $user): int { + DB::flushQueryLog(); + DB::enableQueryLog(); + + signedApiRequest($keyPair, 'GET', route('api-user-followers-you-know.index', $user))->assertOk(); + + return count(DB::getQueryLog()); + }; + + // The first signed request also syncs the user's keys with GitHub... + $queries(); + + $follower = User::factory()->create(['bio' => 'Thanks @taylorotwell']); + $user->followers()->attach($follower); + $viewer->following()->attach($follower); + $withOne = $queries(); + + $more = User::factory()->count(5)->create(['bio' => 'Thanks @taylorotwell']); + $user->followers()->attach($more); + $viewer->following()->attach($more); + + expect($queries())->toBe($withOne); +}); + +it('lists no followers you know across a block for a signed request', function (Closure $block, string $code, bool $showsUser): void { + $viewer = User::factory()->create(); + $user = User::factory()->create(); + + $block($viewer, $user); + + signedApiRequest(apiKeyPairFor($viewer), 'GET', route('api-user-followers-you-know.index', $user)) + ->assertForbidden() + ->assertJsonPath('code', $code) + ->assertJsonPath('user.id', $showsUser ? $user->id : null) + ->assertJsonMissingPath('data'); +})->with([ + 'blocking' => [fn (User $viewer, User $user) => $viewer->blocking()->attach($user), 'user_blocked', true], + 'blocked' => [fn (User $viewer, User $user) => $user->blocking()->attach($viewer), 'user_unavailable', false], +]); + +it('returns not found for unknown handles', function (): void { + signedApiRequest(apiKeyPairFor(User::factory()->create()), 'GET', '/api/v1/users/missing/followers-you-know')->assertNotFound(); +}); diff --git a/tests/Feature/Controllers/Api/UserFollowingControllerTest.php b/tests/Feature/Controllers/Api/UserFollowingControllerTest.php index 877f6226d4..b94a0da819 100644 --- a/tests/Feature/Controllers/Api/UserFollowingControllerTest.php +++ b/tests/Feature/Controllers/Api/UserFollowingControllerTest.php @@ -32,6 +32,19 @@ ->assertJsonPath('data.0.lane', $mutual->lane()); }); +it('links the profiles the bio of each person followed mentions, as their profile does', function (): void { + $user = User::factory()->create(); + User::factory()->create(['handle' => 'TaylorOtwell']); + $user->following()->attach(User::factory()->create(['bio' => 'Thanks @taylorotwell']), ['created_at' => now()->subMinute()]); + $user->following()->attach(User::factory()->create(['bio' => 'Ships on Fridays.', 'company' => null])); + + $response = signedApiRequest(apiKeyPairFor(User::factory()->create()), 'GET', route('api-user-following.index', $user)) + ->assertOk() + ->assertJsonPath('data.1.bio_profiles', ['taylorotwell' => 'TaylorOtwell']); + + expect(json_decode($response->getContent(), flags: JSON_THROW_ON_ERROR)->data[0]->bio_profiles)->toEqual(new stdClass()); +}); + it('pages through the people a user follows 30 at a time', function (): void { $user = User::factory()->create(); $followed = User::factory()->count(31)->create(); diff --git a/tests/Feature/Controllers/Api/UserMutualsControllerTest.php b/tests/Feature/Controllers/Api/UserMutualsControllerTest.php new file mode 100644 index 0000000000..850e292b9c --- /dev/null +++ b/tests/Feature/Controllers/Api/UserMutualsControllerTest.php @@ -0,0 +1,109 @@ +create(['handle' => 'octocat']); + + $this->getJson('/api/v1/users/octocat/mutuals')->assertUnauthorized(); +}); + +it('lists the people a user follows who follow them back, newest follow first', function (): void { + $viewer = User::factory()->create(); + $user = User::factory()->create(); + User::factory()->create(['handle' => 'TaylorOtwell']); + $earlier = User::factory()->create(['bio' => 'Thanks @taylorotwell']); + $later = User::factory()->create(['bio' => 'Ships on Fridays.', 'company' => null]); + $user->following()->attach($earlier, ['created_at' => now()->subMinute()]); + $user->following()->attach($later); + $user->followers()->attach([$earlier->id, $later->id]); + $user->following()->attach(User::factory()->create()); + $user->followers()->attach(User::factory()->create()); + $viewer->following()->attach($earlier); + $viewer->followers()->attach($later); + + $response = signedApiRequest(apiKeyPairFor($viewer), 'GET', route('api-user-mutuals.index', $user)) + ->assertOk() + ->assertJsonPath('data.*.id', [$later->id, $earlier->id]) + ->assertJsonPath('data.*.is_followed', [false, true]) + ->assertJsonPath('data.*.follows_you', [true, false]) + ->assertJsonPath('data.1.bio_profiles', ['taylorotwell' => 'TaylorOtwell']) + ->assertJsonMissingPath('data.0.email') + ->assertJsonPath('meta.next_cursor', null); + + expect(json_decode($response->getContent(), flags: JSON_THROW_ON_ERROR)->data[0]->bio_profiles)->toEqual(new stdClass()); +}); + +it('pages through mutuals 30 at a time with a cursor, by id within the same moment', function (): void { + $this->freezeTime(); + $keyPair = apiKeyPairFor(User::factory()->create()); + $user = User::factory()->create(); + $mutuals = User::factory()->count(31)->create(); + + foreach ($mutuals as $mutual) { + $user->following()->attach($mutual); + $user->followers()->attach($mutual); + } + + $first = signedApiRequest($keyPair, 'GET', route('api-user-mutuals.index', $user)) + ->assertOk() + ->assertJsonCount(30, 'data') + ->assertJsonPath('meta.per_page', 30); + + signedApiRequest($keyPair, 'GET', $first->json('links.next')) + ->assertOk() + ->assertJsonPath('data.*.id', [$mutuals->sortByDesc('id')->last()->id]) + ->assertJsonPath('meta.next_cursor', null); +}); + +it('loads a page of mutuals without a query per mutual', function (): void { + $keyPair = apiKeyPairFor(User::factory()->create()); + $user = User::factory()->create(); + User::factory()->create(['handle' => 'taylorotwell']); + + $queries = function () use ($keyPair, $user): int { + DB::flushQueryLog(); + DB::enableQueryLog(); + + signedApiRequest($keyPair, 'GET', route('api-user-mutuals.index', $user))->assertOk(); + + return count(DB::getQueryLog()); + }; + + // The first signed request also syncs the user's keys with GitHub... + $queries(); + + $mutual = User::factory()->create(['bio' => 'Thanks @taylorotwell']); + $user->following()->attach($mutual); + $user->followers()->attach($mutual); + $withOne = $queries(); + + $more = User::factory()->count(5)->create(['bio' => 'Thanks @taylorotwell']); + $user->following()->attach($more); + $user->followers()->attach($more); + + expect($queries())->toBe($withOne); +}); + +it('lists no mutuals of a profile across a block for a signed request', function (Closure $block, string $code, bool $showsUser): void { + $viewer = User::factory()->create(); + $user = User::factory()->create(); + + $block($viewer, $user); + + signedApiRequest(apiKeyPairFor($viewer), 'GET', route('api-user-mutuals.index', $user)) + ->assertForbidden() + ->assertJsonPath('code', $code) + ->assertJsonPath('user.id', $showsUser ? $user->id : null) + ->assertJsonMissingPath('data'); +})->with([ + 'blocking' => [fn (User $viewer, User $user) => $viewer->blocking()->attach($user), 'user_blocked', true], + 'blocked' => [fn (User $viewer, User $user) => $user->blocking()->attach($viewer), 'user_unavailable', false], +]); + +it('returns not found for unknown handles', function (): void { + signedApiRequest(apiKeyPairFor(User::factory()->create()), 'GET', '/api/v1/users/missing/mutuals')->assertNotFound(); +}); diff --git a/tests/Unit/Queries/BioProfilesQueryTest.php b/tests/Unit/Queries/BioProfilesQueryTest.php index 08d3262912..974ae3a7a3 100644 --- a/tests/Unit/Queries/BioProfilesQueryTest.php +++ b/tests/Unit/Queries/BioProfilesQueryTest.php @@ -23,3 +23,28 @@ expect(resolve(BioProfilesQuery::class)->get($user))->toBe([]); expect(DB::getQueryLog())->toBe([]); }); + +it('finds the profiles each user mentions for a whole page in one query', function (): void { + Organization::factory()->create(['handle' => 'Laravel']); + User::factory()->create(['handle' => 'taylorotwell']); + $first = User::factory()->create(['bio' => 'Thanks @TaylorOtwell', 'company' => null]); + $second = User::factory()->create(['bio' => 'Thanks @taylorotwell', 'company' => '@laravel']); + $quiet = User::factory()->create(['bio' => 'Nothing to see', 'company' => null]); + + DB::enableQueryLog(); + + expect(resolve(BioProfilesQuery::class)->getMany([$first, $second, $quiet]))->toEqual([ + $first->id => ['taylorotwell' => 'taylorotwell'], + $second->id => ['taylorotwell' => 'taylorotwell', 'laravel' => 'Laravel'], + $quiet->id => [], + ])->and(DB::getQueryLog())->toHaveCount(1); +}); + +it('asks nothing when no user on the page mentions anyone', function (): void { + $users = User::factory()->count(2)->create(['bio' => 'Building things', 'company' => null]); + + DB::enableQueryLog(); + + expect(resolve(BioProfilesQuery::class)->getMany($users))->toBe([$users[0]->id => [], $users[1]->id => []]) + ->and(DB::getQueryLog())->toBe([]); +});