Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ Sources: [GitHub action](.github/actions/commit/action.yml).

### Public read API and Atom feeds

The read-only JSON API at `/api/v1` requires no authentication or token, except for who follows whom. Read a public profile at `/api/v1/users/{handle}`, that user's commits at `/api/v1/users/{handle}/commits`, or one commit at `/api/v1/commits/{commit}`. `/api/v1/users/{handle}/followers` and `/following` list people the way the profile's people lists do, newest follow first, with each person's lane and whether you follow each other, and `/api/v1/users/{handle}/following/organizations` lists the organizations they follow the same way, with whether you follow each one; like on the web, they are for members only and need a [signed request](#signed-api-and-devices). Add `?replies=1` to the user-commits endpoint to read their replies instead of top-level commits. Lists use cursor pagination: 20 commits, or 30 people or organizations, per page. Only public approved, non-deleted content is returned, not private profile data such as email. Unsigned requests are limited to **60 requests per minute per IP** and cannot create posts, follow, or star; terminal posting and the [signed API](#signed-api-and-devices) are separate signed interfaces.
The read-only JSON API at `/api/v1` requires no authentication or token, except for who follows whom. Read a public profile at `/api/v1/users/{handle}`, that user's commits at `/api/v1/users/{handle}/commits`, or one commit at `/api/v1/commits/{commit}`. A [link's page](#links-link-cards-and-embedded-players) is at `/api/v1/links/` followed by the link as its web page writes it, with its commits and, beside them, the link, its stats and the sort; a link written another way gets the same answer as the link as commits store it, with no redirect. `/api/v1/users/{handle}/followers` and `/following` list people the way the profile's people lists do, newest follow first, with each person's lane and whether you follow each other, and `/api/v1/users/{handle}/following/organizations` lists the organizations they follow the same way, with whether you follow each one; like on the web, they are for members only and need a [signed request](#signed-api-and-devices). Add `?replies=1` to the user-commits endpoint to read their replies instead of top-level commits. Lists use cursor pagination: 20 commits, or 30 people or organizations, per page. Only public approved, non-deleted content is returned, not private profile data such as email. Unsigned requests are limited to **60 requests per minute per IP** and cannot create posts, follow, or star; terminal posting and the [signed API](#signed-api-and-devices) are separate signed interfaces.

Subscribe in a feed reader to `/@{handle}/feed.atom` for a profile's latest **50 approved top-level commits**, including image enclosures. Feeds are public and can be cached for five minutes.

Expand Down
48 changes: 48 additions & 0 deletions app/Http/Controllers/Api/LinkController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Requests\ShowApiLinkRequest;
use App\Http\Resources\CommitResource;
use App\Models\LinkPreview;
use App\Models\User;
use App\Queries\LinkCommitsQuery;
use App\Queries\ReplyPreviewsQuery;
use App\Services\LinkPages;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Pagination\CursorPaginator;
use Illuminate\Pagination\Paginator;

final readonly class LinkController
{
/**
* The link's page as the web shows it to the signed user, or to a guest: its commits with the link, its stats and
* the sort. A card no commit the viewer may see uses shows nothing of what it was.
*/
public function show(ShowApiLinkRequest $request, #[CurrentUser] ?User $currentUser, LinkCommitsQuery $commits, ReplyPreviewsQuery $replyPreviews, LinkPages $pages): AnonymousResourceCollection
{
$url = $request->link();
$isNewestFirst = $request->isNewestFirst();
$link = LinkPreview::query()->where('url_hash', hash('sha256', $url))->first();
$stats = $link instanceof LinkPreview ? $commits->stats($link, $currentUser) : ['commits' => 0, 'people' => 0];
$link = $stats['commits'] > 0 ? $link : null;

$page = new CursorPaginator([], 20, options: ['path' => Paginator::resolveCurrentPath()]);

if ($link instanceof LinkPreview) {
$page = $commits->builder($link, $currentUser, $isNewestFirst)->cursorPaginate(20)->appends($request->only('sort'));
$replyPreviews->load($page->items(), $currentUser);
}

return CommitResource::collection($page)->additional([
'url' => $url,
'page_url' => $pages->url($url),
'link' => $link,
'stats' => $stats,
'sort' => $isNewestFirst ? 'latest' : 'top',
]);
}
}
52 changes: 52 additions & 0 deletions app/Http/Requests/ShowApiLinkRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Services\CanonicalUrls;
use Illuminate\Foundation\Http\FormRequest;

final class ShowApiLinkRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}

/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'url' => ['required', 'string'],
'sort' => ['nullable', 'string', 'in:top,latest'],
];
}

/**
* @return array<string, mixed>
*/
public function validationData(): array
{
return ['url' => $this->route('url'), 'sort' => $this->query('sort')];
}

/**
* The link as commits store it. A link written another way is answered as that link instead of redirected, since a
* signed request's signature covers the path.
*/
public function link(): string
{
$url = $this->route('url');
assert(is_string($url));

return resolve(CanonicalUrls::class)->canonical('https://'.$url);
}

public function isNewestFirst(): bool
{
return $this->query('sort') === 'latest';
}
}
4 changes: 4 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use App\Http\Controllers\Api\IssueController;
use App\Http\Controllers\Api\IssueSuggestionController;
use App\Http\Controllers\Api\JoinedGuildController;
use App\Http\Controllers\Api\LinkController;
use App\Http\Controllers\Api\LiveFollowingController;
use App\Http\Controllers\Api\LogController;
use App\Http\Controllers\Api\MentionSuggestionController;
Expand Down Expand Up @@ -140,6 +141,9 @@
->name('api-organization-commit.index');
Route::get('organizations/{handle}/mentions', [OrganizationMentionController::class, 'index'])
->name('api-organization-mention.index');
Route::get('links/{url}', [LinkController::class, 'show'])
->where('url', '.+')
->name('api-link.show');

// Mentioned profiles: the user or organization a commit's or message's mention captured, by the id it carries,
// as the web's mention links open them, so they still lead there once they rename...
Expand Down
144 changes: 144 additions & 0 deletions tests/Feature/Controllers/Api/LinkControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

declare(strict_types=1);

use App\Models\Commit;
use App\Models\LinkPreview;
use App\Models\Message;
use App\Models\User;
use App\Services\LinkPages;

function apiLinkPage(string $url): string
{
$page = resolve(LinkPages::class)->url($url);
assert(is_string($page));

return url('api/v1/links/'.mb_substr($page, mb_strlen(url('link').'/')));
}

it('responds with the approved commits about a link and what its page shows', function (): void {
$link = LinkPreview::factory()->fetched()->create(['url' => 'https://wiki.php.net/rfc/pipe-operator']);
$approved = Commit::factory()->create(['link_preview_id' => $link->id]);
Commit::factory()->pending()->create(['link_preview_id' => $link->id]);

$this->getJson(apiLinkPage($link->url))
->assertOk()
->assertJsonPath('url', 'https://wiki.php.net/rfc/pipe-operator')
->assertJsonPath('page_url', url('link/wiki.php.net/rfc/pipe-operator'))
->assertJsonPath('link.url', 'https://wiki.php.net/rfc/pipe-operator')
->assertJsonPath('stats', ['commits' => 1, 'people' => 1])
->assertJsonPath('sort', 'top')
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $approved->id)
->assertJsonMissingPath('data.0.starred');
});

it('lists the most starred commits first, then the newest, or the newest first', function (): void {
$link = LinkPreview::factory()->create(['url' => 'https://dev-null.sh']);
$newest = Commit::factory()->create(['link_preview_id' => $link->id, 'created_at' => now()->subHour()]);
$favourite = Commit::factory()->create(['link_preview_id' => $link->id, 'created_at' => now()->subDays(2)]);
$older = Commit::factory()->create(['link_preview_id' => $link->id, 'created_at' => now()->subDay()]);
$favourite->stars()->attach(User::factory()->count(2)->create());

expect($this->getJson(apiLinkPage($link->url))->assertJsonPath('sort', 'top')->json('data.*.id'))
->toBe([$favourite->id, $newest->id, $older->id])
->and($this->getJson(apiLinkPage($link->url).'?sort=latest')->assertJsonPath('sort', 'latest')->json('data.*.id'))
->toBe([$newest->id, $older->id, $favourite->id]);
});

it('shows a signed request the commits as the web shows them to that user', function (): void {
$viewer = User::factory()->create();
$blocked = User::factory()->create();
$viewer->blocking()->attach($blocked);
$link = LinkPreview::factory()->create(['url' => 'https://dev-null.sh']);
$starred = Commit::factory()->create(['link_preview_id' => $link->id]);
$starred->stars()->attach($viewer);
Commit::factory()->for($blocked)->create(['link_preview_id' => $link->id]);

signedApiRequest(apiKeyPairFor($viewer), 'GET', apiLinkPage($link->url))
->assertOk()
->assertJsonPath('stats', ['commits' => 1, 'people' => 1])
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $starred->id)
->assertJsonPath('data.0.starred', true);
});

it('reads a link whose query, fragment and ending slash its page escapes', function (): void {
$link = LinkPreview::factory()->create(['url' => 'https://example.com/docs/?page=2&q=100%25#top']);
Commit::factory()->create(['link_preview_id' => $link->id]);
$folder = LinkPreview::factory()->create(['url' => 'https://example.com/docs/']);
Commit::factory()->create(['link_preview_id' => $folder->id]);

$this->getJson(apiLinkPage($link->url))->assertOk()
->assertJsonPath('url', 'https://example.com/docs/?page=2&q=100%25#top')
->assertJsonCount(1, 'data');

$this->getJson(apiLinkPage($folder->url))->assertOk()
->assertJsonPath('url', 'https://example.com/docs/')
->assertJsonCount(1, 'data');
});

it('answers a link written another way with the link as commits store it', function (): void {
$link = LinkPreview::factory()->create(['url' => 'https://wiki.php.net/rfc/pipe-operator']);
Commit::factory()->create(['link_preview_id' => $link->id]);

$this->getJson(url('api/v1/links/WIKI.php.net/rfc/pipe-operator'))
->assertOk()
->assertJsonPath('url', 'https://wiki.php.net/rfc/pipe-operator')
->assertJsonPath('page_url', url('link/wiki.php.net/rfc/pipe-operator'))
->assertJsonCount(1, 'data');
});

it('shows no commits for a link nobody used as their card', function (): void {
$this->getJson(url('api/v1/links/example.com/nothing'))
->assertOk()
->assertJsonPath('link', null)
->assertJsonPath('stats', ['commits' => 0, 'people' => 0])
->assertJsonCount(0, 'data')
->assertJsonPath('meta.next_cursor', null);
});

it('shows nothing of a card the viewer may see no commit use', function (): void {
$link = LinkPreview::factory()->fetched()->create(['url' => 'https://example.com/private', 'title' => 'A private plan']);
Message::factory()->create(['link_preview_id' => $link->id]);
Commit::factory()->pending()->create(['link_preview_id' => $link->id]);

$this->getJson(apiLinkPage($link->url))
->assertOk()
->assertDontSee('A private plan')
->assertJsonPath('link', null)
->assertJsonPath('stats', ['commits' => 0, 'people' => 0])
->assertJsonCount(0, 'data');
});

it('rejects a sort it does not know', function (): void {
$this->getJson(url('api/v1/links/dev-null.sh').'?sort=hot')->assertUnprocessable()->assertJsonValidationErrors('sort');
});

it('pages the commits twenty at a time', function (): void {
$link = LinkPreview::factory()->create(['url' => 'https://dev-null.sh']);
Commit::factory()->count(21)->create(['link_preview_id' => $link->id]);

$response = $this->getJson(apiLinkPage($link->url))
->assertOk()
->assertJsonCount(20, 'data')
->assertJsonPath('stats.commits', 21);

expect($response->json('meta.next_cursor'))->toBeString();
});

it('keeps the latest first on the next page', function (): void {
$link = LinkPreview::factory()->create(['url' => 'https://dev-null.sh']);
$oldest = Commit::factory()->create(['link_preview_id' => $link->id, 'created_at' => now()->subDay()]);
Commit::factory()->count(20)->create(['link_preview_id' => $link->id]);

$next = $this->getJson(apiLinkPage($link->url).'?sort=latest')->json('links.next');

expect($next)->toContain('sort=latest');

$this->getJson($next)
->assertOk()
->assertJsonPath('sort', 'latest')
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $oldest->id);
});