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
28 changes: 23 additions & 5 deletions app/Actions/CreateExport.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
* @phpstan-type ExportPollVote array{commit_id: string, option: string, created_at: string}
* @phpstan-type ExportMessage array{to: string|null, body: string, voice: string|null, created_at: string}
* @phpstan-type ExportUser array{handle: string}
* @phpstan-type ExportFollow array{handle: string, notify_live: bool}
* @phpstan-type ExportActiveDay array{date: string, web_app: bool, native_mobile_app: bool, lite_mobile_app: bool, mac_app: bool, other_app: bool}
* @phpstan-type UserExport array{
* schema_version: int,
Expand All @@ -49,8 +50,8 @@
* polls: Generator<int, ExportPoll>,
* poll_votes: Generator<int, ExportPollVote>,
* stars: Generator<int, string>,
* following: Generator<int, ExportUser>,
* followers: Generator<int, ExportUser>,
* following: Generator<int, ExportFollow>,
* followers: Generator<int, ExportFollow>,
* muting: Generator<int, ExportUser>,
* blocking: Generator<int, ExportUser>,
* dismissed_suggestions: Generator<int, ExportUser>,
Expand Down Expand Up @@ -86,7 +87,7 @@
public function handle(User $user): array
{
return [
'schema_version' => 9,
'schema_version' => 10,
'exported_at' => now()->toIso8601String(),
'profile' => [
'github_id' => $user->github_id,
Expand All @@ -110,6 +111,7 @@ public function handle(User $user): array
'pasteis_given_today' => $user->pasteis_given_today,
'pasteis_given_on' => $user->pasteis_given_on?->toDateString(),
'remotes_enabled' => $user->remotes_enabled,
'live_notifications_enabled' => $user->live_notifications_enabled,
'remotes_from' => $user->remotes_from->value,
'pull_receipts' => $user->pull_receipts,
'push_follows' => $user->push_follows,
Expand All @@ -133,8 +135,8 @@ public function handle(User $user): array
'polls' => $this->polls($user),
'poll_votes' => $this->pollVotes($user),
'stars' => $this->stars($user),
'following' => $this->handles($user->following()),
'followers' => $this->handles($user->followers()),
'following' => $this->handlesWithLive($user->following()),
'followers' => $this->handlesWithLive($user->followers()),
'muting' => $this->handles($user->muting()),
'blocking' => $this->handles($user->blocking()),
'dismissed_suggestions' => $this->handles($user->dismissedSuggestions()),
Expand Down Expand Up @@ -429,6 +431,22 @@ private function handles(BelongsToMany $users): Generator
}
}

/**
* @param BelongsToMany<User, User> $users
* @return Generator<int, ExportFollow>
*/
private function handlesWithLive(BelongsToMany $users): Generator
{
/** @var LazyCollection<int, object{handle: string, notify_live: bool|int|string|null}> $users */
$users = $users->join('profiles', 'profiles.id', '=', 'users.id')->toBase()
->select(['users.id', 'profiles.handle', 'follows.notify_live'])
->lazyById(500, 'users.id', 'id');

foreach ($users as $user) {
yield ['handle' => $user->handle, 'notify_live' => (bool) $user->notify_live];
}
}

/**
* @return array<int, array{handle: string, role: string, joined_at: string}>
*/
Expand Down
1 change: 1 addition & 0 deletions app/Actions/CreateUserFollow.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function handle(User $follower, User $followed): void
$follower->following()->newPivotStatement()->insertOrIgnore([
'follower_id' => $follower->id,
'followed_id' => $followed->id,
'notify_live' => true,
'created_at' => now(),
'updated_at' => now(),
]);
Expand Down
75 changes: 66 additions & 9 deletions app/Actions/UpdateUserLive.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,81 @@

namespace App\Actions;

use App\Dto\LiveStream;
use App\Enums\LivePlatform;
use App\Enums\NotificationType;
use App\Enums\UserUpdate;
use App\Events\ProfilesUpdated;
use App\Events\UsersUpdated;
use App\Models\Notification;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

final readonly class UpdateUserLive
{
public function handle(User $user, LivePlatform $platform, string $url, int $hours): void
{
$user->update([
'live_platform' => $platform,
'live_url' => $platform->driver()->stream($url)->url,
'live_ends_at' => now()->addHours($hours),
]);

event(new ProfilesUpdated([$user->id], changesLive: true));
event(new UsersUpdated([$user->id], UserUpdate::Account));
event(new UsersUpdated($user->followers()->pluck('users.id'), UserUpdate::Live));
DB::transaction(function () use ($user, $platform, $url, $hours): void {
// Two go-live requests at once must not each fan out, so the previous stream is read from the locked row.
$locked = User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();
$wasLive = $locked->liveStream() instanceof LiveStream;
$endsAt = now()->addHours($hours);

// Update the caller's model as before, so controllers answer with the stream they just saved, but only
// after the lock has decided whether this is a new stream.
$user->update([
'live_platform' => $platform,
'live_url' => $platform->driver()->stream($url)->url,
'live_ends_at' => $endsAt,
]);

event(new ProfilesUpdated([$user->id], changesLive: true));
event(new UsersUpdated([$user->id], UserUpdate::Account));
event(new UsersUpdated($user->followers()->pluck('users.id'), UserUpdate::Live));

if (! $wasLive) {
$this->notifyFollowers($user, $endsAt);
}
});
}

private function notifyFollowers(User $user, CarbonInterface $endsAt): void
{
$followerIds = $user->followers()
->wherePivot('notify_live', true)
->where('users.live_notifications_enabled', true)
->whereNotIn('users.id', $user->mutedBy()->newPivotQuery()->select('muter_id'))
->whereNotIn('users.id', $user->idsAcrossBlocks())
->pluck('users.id')
->map(fn (mixed $id): string => is_scalar($id) ? (string) $id : '')
->values()
->all();

if ($followerIds === []) {
return;
}

$now = now();
// One key per start; the unique index then dedupes only repeated inserts for that same start.
$key = 'live_started:'.$user->id.':'.$endsAt->getTimestamp().':'.Str::uuid7()->toString();

$notifications = array_map(fn (string $followerId): array => [
'id' => Str::uuid7()->toString(),
'recipient_id' => $followerId,
'actor_id' => $user->id,
'type' => NotificationType::LiveStarted->value,
'commit_id' => null,
'key' => $key,
'created_at' => $now,
'updated_at' => $now,
], $followerIds);

foreach (array_chunk($notifications, 500) as $chunk) {
Notification::query()->insertOrIgnore($chunk);
}

event(new UsersUpdated($followerIds, UserUpdate::Notifications));
}
}
21 changes: 21 additions & 0 deletions app/Actions/UpdateUserLiveNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace App\Actions;

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

final readonly class UpdateUserLiveNotification
{
public function handle(User $follower, User $followed, bool $notifyLive): void
{
$follower->following()->updateExistingPivot($followed->id, [
'notify_live' => $notifyLive,
]);

event(new UsersUpdated([$follower->id], UserUpdate::Account));
}
}
28 changes: 28 additions & 0 deletions app/Actions/UpdateUserLiveNotifications.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace App\Actions;

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

final readonly class UpdateUserLiveNotifications
{
public function handle(User $user, bool $enabled): void
{
$user->update(['live_notifications_enabled' => $enabled]);

if (! $enabled) {
$user->notifications()
->where('type', NotificationType::LiveStarted)
->whereNull('read_at')
->update(['read_at' => now()]);
}

event(new UsersUpdated([$user->id], UserUpdate::Account));
event(new UsersUpdated([$user->id], UserUpdate::Notifications));
}
}
1 change: 1 addition & 0 deletions app/Enums/NotificationType.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
enum NotificationType: string
{
case Followed = 'followed';
case LiveStarted = 'live_started';
case Replied = 'replied';
case Mentioned = 'mentioned';
case Approved = 'approved';
Expand Down
1 change: 1 addition & 0 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser
'isFollowing' => $relationship(fn (): bool => $currentUser?->isFollowing($user) ?? false),
'followsYou' => $relationship(fn (): bool => $currentUser instanceof User && $user->isFollowing($currentUser)),
'isMuting' => $relationship(fn (): bool => $currentUser?->isMuting($user) ?? false),
'isNotifyingLive' => $relationship(fn (): bool => $currentUser?->isNotifyingLive($user) ?? false),
'followersYouKnow' => fn (): ?array => $currentUser instanceof User && $currentUser->isNot($user)
? $followersYouKnow->preview($user, $currentUser)
: null,
Expand Down
28 changes: 28 additions & 0 deletions app/Http/Controllers/UserLiveNotificationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Actions\UpdateUserLiveNotification;
use App\Http\Requests\CreateUserLiveNotificationRequest;
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\RedirectResponse;

final readonly class UserLiveNotificationController
{
public function store(CreateUserLiveNotificationRequest $request, #[CurrentUser] User $currentUser, User $user, UpdateUserLiveNotification $action): RedirectResponse
{
$action->handle($currentUser, $user, true);

return back();
}

public function destroy(CreateUserLiveNotificationRequest $request, #[CurrentUser] User $currentUser, User $user, UpdateUserLiveNotification $action): RedirectResponse
{
$action->handle($currentUser, $user, false);

return back();
}
}
21 changes: 21 additions & 0 deletions app/Http/Controllers/UserLiveNotificationsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Actions\UpdateUserLiveNotifications;
use App\Http\Requests\UpdateUserLiveNotificationsRequest;
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\RedirectResponse;

final readonly class UserLiveNotificationsController
{
public function update(UpdateUserLiveNotificationsRequest $request, #[CurrentUser] User $user, UpdateUserLiveNotifications $action): RedirectResponse
{
$action->handle($user, $request->boolean('enabled'));

return back();
}
}
19 changes: 19 additions & 0 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
use App\Enums\EventTheme;
use App\Enums\Feature;
use App\Enums\Log;
use App\Enums\NotificationType;
use App\Enums\RepliesPerPage;
use App\Enums\UserUpdate;
use App\Http\Requests\ListNotificationsRequest;
use App\Http\Resources\ShownStreams;
use App\Models\Commit;
use App\Models\Notification;
use App\Models\Organization;
use App\Models\User;
use App\Queries\BioProfilesQuery;
Expand Down Expand Up @@ -136,6 +138,7 @@ public function share(Request $request): array
->all() : [], UserUpdate::Account),
'isAdmin' => $isAdmin,
'automaticTranslation' => $live(fn (): bool => $user->automatic_translation ?? true, UserUpdate::Account),
'liveNotificationsEnabled' => $live(fn (): bool => $user instanceof User && $user->live_notifications_enabled, UserUpdate::Account),
// The language translations are read in, saved or from the browser, so a change saved elsewhere reaches
// the translations already shown.
'translationLanguage' => $live(fn (): string => resolve(CommitTranslations::class)->language(), UserUpdate::Account),
Expand All @@ -144,6 +147,22 @@ public function share(Request $request): array
'log' => $live(fn (): ?Log => $request->user()?->log, UserUpdate::Account),
// Each browser filters notifications its own way, and reloading the count goes through its cookie.
'unreadNotificationsCount' => $live(fn (): int => $user instanceof User ? resolve(NotificationGroupsQuery::class)->unreadCount($user, ListNotificationsRequest::rememberedType($request, $user)) : 0, UserUpdate::Notifications),
// The browser plays the live sound when this changes, so it needs the newest one even once read.
'latestLiveNotificationId' => $live(function () use ($user): ?string {
if (! $user instanceof User) {
return null;
}

$id = Notification::query()
->where('recipient_id', $user->id)
->where('type', NotificationType::LiveStarted)
->relevant()
->latest()
->latest('id')
->value('id');

return is_string($id) ? $id : null;
}, 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 ? [
'from' => $user->remotes_from,
Expand Down
30 changes: 30 additions & 0 deletions app/Http/Requests/CreateUserLiveNotificationRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;

final class CreateUserLiveNotificationRequest extends FormRequest
{
public function authorize(): bool
{
$follower = $this->user();
assert($follower instanceof User);

$followed = $this->route('user');
assert($followed instanceof User);

return $follower->isNot($followed) && $follower->isFollowing($followed);
}

/**
* @return array{}
*/
public function rules(): array
{
return [];
}
}
25 changes: 25 additions & 0 deletions app/Http/Requests/UpdateUserLiveNotificationsRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

/**
* @return array<string, list<string>>
*/
public function rules(): array
{
return [
'enabled' => ['required', 'boolean'],
];
}
}
Loading