Skip to content
Draft
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
3 changes: 2 additions & 1 deletion KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ Sources: [Pastéis setting](resources/js/components/pasteis-mode-setting.tsx), [

### Notifications

Open **Notifications** to read in-app activity: follows, replies, quotes, mentions, stars, first commits of people you follow, and moderation messages about rejected commits (approvals do not notify). The navigation shows unread activity and checks for more every 30 seconds. While you have unread notifications or messages, the browser tab's icon shows an orange dot; a tab in the background checks about every five minutes. Related activity is grouped, with expandable details: stars per commit, follows per day, and replies and mentions per thread. Filters (Replies, Quotes, Stars, Mentions, Follows, Moderation) are remembered, and the unread count follows them. Opening the inbox marks all notifications read. You can follow back or unfollow from follower notifications.
Open **Notifications** to read in-app activity: follows, replies, quotes, mentions, stars, first commits of people you follow, and moderation messages about rejected commits (approvals do not notify). The navigation shows unread activity and checks for more every 30 seconds. While you have unread notifications or messages, the browser tab's icon shows an orange dot; a tab in the background checks about every five minutes. Related activity is grouped, with expandable details: stars per commit, follows per day, and replies and mentions per thread. Filters (Replies, Quotes, Stars, Mentions, Follows, Moderation) are remembered with your account, so every browser and the apps show and count the same ones, and the unread count follows them. Opening the inbox marks all notifications read. You can follow back or unfollow from follower notifications.

When someone you follow makes their first commit, you get a notification for it under **All**, so a newcomer's first post gets seen and answered. It comes once per person, after approval, and never for replies.

Expand Down Expand Up @@ -586,6 +586,7 @@ An app can use the same `/api/v1` for you with signed requests. It keeps an SSH
A signed request sees what the web shows you, such as your own pending commits and your organizations'. It can also, with the web's validation, moderation, and rate limits:

- read your account, logs, replies, notifications (including grouped activity), and starred commits;
- choose which kinds of notifications you see and the unread count counts, the same choice the web's notification filters save;
- read the organizations you are a member of, your role in each, and whether posting as an organization is switched on;
- commit, reply, and quote, with images, and delete your commits, with the same undo window as the web;
- preview commit drafts without publishing them;
Expand Down
1 change: 1 addition & 0 deletions app/Actions/CreateExport.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public function handle(User $user): array
'push_mentions' => $user->push_mentions,
'push_direct_remotes' => $user->push_direct_remotes,
'push_org_remotes' => $user->push_org_remotes,
'notification_types' => $user->notification_types,
'pinned_commit_id' => $user->pinned_commit_id,
'live_platform' => $user->live_platform?->value,
'live_url' => $user->live_url,
Expand Down
27 changes: 27 additions & 0 deletions app/Actions/UpdateUserNotificationTypes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Actions;

use App\Enums\UserUpdate;
use App\Events\UsersUpdated;
use App\Models\User;

final readonly class UpdateUserNotificationTypes
{
/**
* Remembers which kinds of notifications the user wants to see, and refreshes the unread count wherever they are
* signed in, since it only counts those kinds.
*/
public function handle(User $user, string $type): void
{
if ($user->notification_types === $type) {
return;
}

$user->update(['notification_types' => $type]);

event(new UsersUpdated([$user->id], UserUpdate::Notifications));
}
}
29 changes: 29 additions & 0 deletions app/Http/Controllers/Api/UserNotificationTypesController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Actions\UpdateUserNotificationTypes;
use App\Http\Requests\UpdateApiUserNotificationTypesRequest;
use App\Models\User;
use App\Queries\NotificationGroupsQuery;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\JsonResponse;

final readonly class UserNotificationTypesController
{
/**
* Saves which kinds of notifications the user wants to see, as choosing them on the web's notifications page does,
* and answers with them and the unread count, which now only counts those kinds.
*/
public function update(UpdateApiUserNotificationTypesRequest $request, #[CurrentUser] User $user, UpdateUserNotificationTypes $action, NotificationGroupsQuery $notifications): JsonResponse
{
$action->handle($user, $request->string('type')->value());

return response()->json([
'data' => ['type' => $user->notificationTypes()],
'unread_notifications_count' => $notifications->unreadCount($user),
])->header('Cache-Control', 'private, no-store');
}
}
4 changes: 3 additions & 1 deletion app/Http/Controllers/Api/UserSettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
/**
* What the web's settings show only the user: their timezone and the language commits are translated into, `null`
* to follow the device, whether commits are translated automatically, the languages they may pick from, whether
* the web shows them its admin pages, which the app only links to, and what they want pushed to their phones.
* the web shows them its admin pages, which the app only links to, what they want pushed to their phones, and which
* kinds of notifications they see, as `?type=` takes them.
*/
public function show(#[CurrentUser] User $user, CommitTranslations $translations): JsonResponse
{
Expand All @@ -32,6 +33,7 @@ public function show(#[CurrentUser] User $user, CommitTranslations $translations
])->sortBy('name')->values()->all(),
'is_admin' => $user->isAdmin(),
'push' => PushPreference::allFor($user),
'notification_types' => $user->notificationTypes(),
]])->header('Cache-Control', 'private, no-store');
}
}
2 changes: 1 addition & 1 deletion app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function share(Request $request): array
'mustReadCommitRules' => $live(fn (): bool => $user instanceof User && $user->commit_rules_accepted_at === null, UserUpdate::Account),
'termsToAccept' => $live(fn (): ?string => $user instanceof User && ! $user->hasAcceptedCurrentTerms() ? config()->string('legal.terms_version') : null, UserUpdate::Account),
'log' => $live(fn (): ?Log => $request->user()?->log, UserUpdate::Account),
// Each browser filters notifications its own way, and reloading the count goes through its cookie.
// Counts only the kinds the user chose to see, taking over a browser's old cookie the first time.
'unreadNotificationsCount' => $live(fn (): int => $user instanceof User ? resolve(NotificationGroupsQuery::class)->unreadCount($user, ListNotificationsRequest::rememberedType($request, $user)) : 0, UserUpdate::Notifications),
'unreadMessagesCount' => $live(fn (): int => $user?->remotes_enabled ? resolve(ConversationsQuery::class)->unreadCount($user) : 0, UserUpdate::Messages, UserUpdate::Inbox),
'remotes' => $live(fn (): ?array => $user?->remotes_enabled ? [
Expand Down
19 changes: 14 additions & 5 deletions app/Http/Requests/ListNotificationsRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Http\Requests;

use App\Actions\UpdateUserNotificationTypes;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Http\FormRequest;
Expand All @@ -14,11 +15,21 @@ final class ListNotificationsRequest extends FormRequest
{
public const string TYPE_RULE = 'regex:/\A(?:all|none|(?:replies|quotes|stars|mentions|follows|moderation)(?:,(?:replies|quotes|stars|mentions|follows|moderation))*)\z/';

/**
* The kinds the user chose, kept on the user so the API counts and lists the same ones. Browsers that still have
* the cookie this used to live in hand it over the first time they're seen.
*/
public static function rememberedType(Request $request, User $user): string
{
$type = $request->cookie('notification_types_'.$user->id, 'all');
$cookie = 'notification_types_'.$user->id;
$type = $request->cookie($cookie);

if ($user->notification_types === null && is_string($type) && preg_match(mb_substr(self::TYPE_RULE, 6), $type) === 1) {
resolve(UpdateUserNotificationTypes::class)->handle($user, $type);
Cookie::queue(Cookie::forget($cookie));
}

return is_string($type) && preg_match(mb_substr(self::TYPE_RULE, 6), $type) === 1 ? $type : 'all';
return $user->notificationTypes();
}

public function authorize(): bool
Expand All @@ -37,11 +48,9 @@ public function rules(): array

public function type(User $user): string
{
$cookie = 'notification_types_'.$user->id;

if ($this->has('type')) {
$type = $this->filled('type') ? $this->string('type')->value() : 'all';
Cookie::queue($cookie, $type, 60 * 24 * 365);
resolve(UpdateUserNotificationTypes::class)->handle($user, $type);

return $type;
}
Expand Down
27 changes: 27 additions & 0 deletions app/Http/Requests/UpdateApiUserNotificationTypesRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

/**
* The kinds to see, as the notifications list takes them in `?type=`.
*
* @return array<string, list<string>>
*/
public function rules(): array
{
return [
'type' => ['required', 'string', ListNotificationsRequest::TYPE_RULE],
];
}
}
11 changes: 11 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
* @property-read bool $push_mentions
* @property-read bool $push_direct_remotes
* @property-read bool $push_org_remotes
* @property-read string|null $notification_types
* @property-read int $pasteis_received
* @property-read int $pasteis_given_today
* @property-read CarbonInterface|null $pasteis_given_on
Expand Down Expand Up @@ -114,6 +115,7 @@
'push_mentions',
'push_direct_remotes',
'push_org_remotes',
'notification_types',
'pasteis_received',
'pasteis_given_today',
'pasteis_given_on',
Expand Down Expand Up @@ -173,6 +175,7 @@ final class User extends Authenticatable
'push_mentions' => true,
'push_direct_remotes' => true,
'push_org_remotes' => true,
'notification_types' => null,
'pasteis_received' => 0,
'pasteis_given_today' => 0,
'pasteis_given_on' => null,
Expand Down Expand Up @@ -501,6 +504,14 @@ public function broadcastChannel(): string
return 'users.'.$this->id;
}

/**
* Which kinds of notifications the user chose to see, as `?type=` takes them, or all of them until they choose.
*/
public function notificationTypes(): string
{
return $this->notification_types ?? 'all';
}

public function isAdmin(): bool
{
/** @var list<string> $admins */
Expand Down
5 changes: 4 additions & 1 deletion app/Queries/NotificationGroupsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,12 @@ public function withStarredCommitImages(CursorPaginator $groups): CursorPaginato
/**
* Whether two unread notifications share a group only depends on what happened between them, so grouping from the
* oldest unread one onward counts the same groups as grouping the whole history, which every page would pay for.
* Only the kinds the user chose to see count, unless another filter is given.
*/
public function unreadCount(User $user, string $type = 'all'): int
public function unreadCount(User $user, ?string $type = null): int
{
$type ??= $user->notificationTypes();

if ($type === 'none') {
return 0;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Which kinds of notifications the user chose to see, as `?type=` takes them: `all`, `none`, or a comma separated
* list. `null` until they choose, which shows them all.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->string('notification_types')->nullable();
});
}
};
4 changes: 4 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
use App\Http\Controllers\Api\UserLiveController;
use App\Http\Controllers\Api\UserModerationHistoryController;
use App\Http\Controllers\Api\UserMuteController;
use App\Http\Controllers\Api\UserNotificationTypesController;
use App\Http\Controllers\Api\UserPasteisModeController;
use App\Http\Controllers\Api\UserProfileController;
use App\Http\Controllers\Api\UserPushPreferencesController;
Expand Down Expand Up @@ -213,6 +214,9 @@
Route::delete('me/push-token', [DevicePushTokenController::class, 'destroy'])->name('api-device-push-token.destroy');
Route::put('me/push-preferences', [UserPushPreferencesController::class, 'update'])->name('api-user-push-preferences.update');

// Which kinds of notifications the user sees, and the unread count counts, as the web's notifications page saves them...
Route::put('me/notification-types', [UserNotificationTypesController::class, 'update'])->name('api-user-notification-types.update');

// Who follows whom, for members like on the web, so scrapers can't walk the graph...
Route::get('users/{user:handle}/followers', [UserFollowersController::class, 'index'])
->name('api-user-followers.index');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

use App\Models\Commit;
use App\Models\Notification;
use App\Models\User;

it('shows every kind until the user chooses', function (): void {
signedApiRequest(apiKeyPairFor(User::factory()->create()), 'GET', route('api-user-settings.show'))
->assertOk()
->assertJsonPath('data.notification_types', 'all');
});

it('saves the kinds the user wants to see, and answers with them and the unread count of only those', function (string $type, int $expected): void {
$user = User::factory()->create();
$keyPair = apiKeyPairFor($user);
Notification::factory()->for($user, 'recipient')->replied(Commit::factory()->for($user)->create())->create();
Notification::factory()->for($user, 'recipient')->starred()->create();
Notification::factory()->for($user, 'recipient')->create();

signedApiRequest($keyPair, 'PUT', route('api-user-notification-types.update'), ['type' => $type])
->assertOk()
->assertHeader('Cache-Control', 'no-store, private')
->assertExactJson(['data' => ['type' => $type], 'unread_notifications_count' => $expected]);

expect($user->refresh()->notification_types)->toBe($type)
->and(signedApiRequest($keyPair, 'GET', route('api-user-settings.show'))->json('data.notification_types'))->toBe($type);
})->with([
'all' => ['all', 3],
'one kind' => ['replies', 1],
'several kinds' => ['replies,stars', 2],
'none' => ['none', 0],
]);

it('counts only the chosen kinds everywhere the API answers with the unread count, and lists them by default', function (): void {
$user = User::factory()->create();
$keyPair = apiKeyPairFor($user);
$reply = Notification::factory()->for($user, 'recipient')->replied(Commit::factory()->for($user)->create())->create();
Notification::factory()->for($user, 'recipient')->create();

signedApiRequest($keyPair, 'PUT', route('api-user-notification-types.update'), ['type' => 'replies'])->assertOk();

signedApiRequest($keyPair, 'GET', route('api-current-user.show'))->assertJsonPath('unread_notifications_count', 1);
signedApiRequest($keyPair, 'PUT', route('api-user-timezone.update'), ['timezone' => 'Europe/Lisbon'])->assertJsonPath('unread_notifications_count', 1);
signedApiRequest($keyPair, 'GET', route('api-notification.index'))
->assertJsonPath('filters.type', 'replies')
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $reply->id);
});

it('saves the kinds the list was asked for, as the web does', function (): void {
$user = User::factory()->create();

signedApiRequest(apiKeyPairFor($user), 'GET', route('api-notification.index', ['type' => 'follows,mentions']))
->assertOk()
->assertJsonPath('filters.type', 'follows,mentions');

expect($user->refresh()->notification_types)->toBe('follows,mentions');
});

it('needs kinds the notifications list knows', function (mixed $type): void {
$user = User::factory()->create(['notification_types' => 'replies']);

signedApiRequest(apiKeyPairFor($user), 'PUT', route('api-user-notification-types.update'), $type === null ? [] : ['type' => $type])
->assertUnprocessable()
->assertJsonValidationErrors('type');

expect($user->refresh()->notification_types)->toBe('replies');
})->with([
'missing' => [null],
'empty' => [''],
'unknown kind' => ['replies,secret'],
'not a string' => [['replies']],
]);

it('rejects requests that are not signed', function (): void {
$this->putJson(route('api-user-notification-types.update'), ['type' => 'none'])->assertUnauthorized();
});
1 change: 1 addition & 0 deletions tests/Feature/Controllers/ExportControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
'push_mentions' => true,
'push_direct_remotes' => true,
'push_org_remotes' => true,
'notification_types' => null,
'pinned_commit_id' => null,
'live_platform' => null,
'live_url' => null,
Expand Down
Loading