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
81 changes: 81 additions & 0 deletions app/Actions/UpdateMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

declare(strict_types=1);

namespace App\Actions;

use App\Enums\UserUpdate;
use App\Events\UsersUpdated;
use App\Jobs\UnfurlLink;
use App\Models\ConversationParticipant;
use App\Models\LinkPreview;
use App\Models\Message;
use App\Queries\MentionedUsersQuery;
use App\Services\EmojiShortcodes;
use App\Services\Urls;
use Illuminate\Support\Facades\DB;

final readonly class UpdateMessage
{
public function __construct(
private EmojiShortcodes $emojiShortcodes,
private MentionedUsersQuery $mentionedUsers,
private Urls $urls,
) {
//
}

/**
* Rewords a message within its edit window: the body, mentions, and link card are recomputed the way pushing
* computes them, everything else stays, and the thread hears about it so the partner sees the new wording live.
*/
public function handle(Message $message, string $body): Message
{
$url = $this->urls->first($body);
$sender = $message->user;

DB::transaction(function () use ($message, $body, $url, $sender): void {
// Read under a lock so overlapping edits serialize: the second one diffs against the first one's
// committed mentions instead of a stale snapshot, and no badge is left behind.
$previousMentions = array_values(Message::query()->whereKey($message->id)->lockForUpdate()->value('mentions') ?? []);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$message->refresh();

$linkPreview = $url === null ? null : LinkPreview::query()->firstOrCreate(['url_hash' => hash('sha256', $url)], ['url' => $url]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

$message->update([
'body' => $this->emojiShortcodes->replace($body),
'mentions' => $this->mentionedUsers->get($body),
'link_preview_id' => $linkPreview?->id,
'edited_at' => now(),
]);

if ($linkPreview instanceof LinkPreview && $linkPreview->fetched_at === null) {
dispatch(new UnfurlLink($linkPreview))->afterCommit();
}

// Mention badges live on a pivot, not in the JSON. Badges are only added for newly mentioned
// recipients and removed for deleted mentions, so a badge the recipient cleared stays cleared.
if ($message->conversation->isOrg()) {
$currentMentions = array_values($message->mentions ?? []);

$message->mentionedUsers()->detach(array_diff($previousMentions, $currentMentions));

$added = array_diff($currentMentions, $previousMentions);

if ($added !== []) {
$message->mentionedUsers()->attach($message->conversation->participants()
->whereIn('user_id', $added)
->where('user_id', '!=', $sender->id)
->where('visible_from_id', '<', $message->id)
->whereNotIn('user_id', $sender->idsAcrossBlocks())
->whereNotIn('user_id', $sender->mutedBy()->newPivotQuery()->select('muter_id'))
->pluck('user_id'));
}
}
});

event(new UsersUpdated(ConversationParticipant::query()->where('conversation_id', $message->conversation_id)->pluck('user_id'), UserUpdate::Messages, ['conversation' => $message->conversation_id]));

return $message->refresh()->load(Message::SHOWN_WITH);
}
}
8 changes: 8 additions & 0 deletions app/Http/Controllers/ConversationMessageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

use App\Actions\CreateConversation;
use App\Actions\CreateMessage;
use App\Actions\UpdateMessage;
use App\Http\Requests\CreateConversationMessageRequest;
use App\Http\Requests\ListConversationMessagesRequest;
use App\Http\Requests\UpdateConversationMessageRequest;
use App\Models\Message;
use App\Models\User;
use App\Queries\ConversationThreadQuery;
use Illuminate\Container\Attributes\CurrentUser;
Expand Down Expand Up @@ -40,4 +43,9 @@ public function store(CreateConversationMessageRequest $request, #[CurrentUser]

return response()->json(['message' => $message], 201);
}

public function update(UpdateConversationMessageRequest $request, User $partner, Message $message, UpdateMessage $action): JsonResponse
{
return response()->json(['message' => $action->handle($message, $request->string('body')->value())]);
}
}
8 changes: 8 additions & 0 deletions app/Http/Controllers/OrgMessageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
namespace App\Http\Controllers;

use App\Actions\CreateMessage;
use App\Actions\UpdateMessage;
use App\Http\Requests\CreateOrgMessageRequest;
use App\Http\Requests\ListOrgMessagesRequest;
use App\Http\Requests\UpdateOrgMessageRequest;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;
use App\Queries\ConversationThreadQuery;
use Illuminate\Container\Attributes\CurrentUser;
Expand Down Expand Up @@ -40,4 +43,9 @@ public function store(CreateOrgMessageRequest $request, #[CurrentUser] User $use

return response()->json(['message' => $message], 201);
}

public function update(UpdateOrgMessageRequest $request, Conversation $org, Message $message, UpdateMessage $action): JsonResponse
{
return response()->json(['message' => $action->handle($message, $request->string('body')->value())]);
}
}
78 changes: 78 additions & 0 deletions app/Http/Requests/UpdateConversationMessageRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\PushAccess;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;
use App\Queries\PushAccessQuery;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;

final class UpdateConversationMessageRequest extends FormRequest
{
/**
* Only the author may reword their own message, only within its edit window, and only where both halves can
* already see it. Editing pushes to the conversation, so it also takes what pushing does: no blocks, and a merged
* request. Anything else reads as missing, except an expired window or an unmerged request, which say so.
*/
public static function authorization(User $user, Message $message, User $partner, PushAccessQuery $access): Response
{
$conversation = Conversation::between($user, $partner);

if (! $user->remotes_enabled || $message->event !== null || ! $message->isVisibleTo($user) || $conversation === null || $message->conversation_id !== $conversation->id) {
return Response::denyAsNotFound();
}

if ($message->user_id !== $user->id) {
return Response::denyAsNotFound();
}

if ($message->voice !== null) {
return Response::deny('Voice notes cannot be edited.');
}

if ($message->editExpired()) {
return Response::deny('Messages can only be edited for 3 minutes after pushing.');
}

if (! $user->canMessage($partner)) {
return Response::denyAsNotFound();
}

return $access->get($user, $partner) === PushAccess::Open
? Response::allow()
: Response::deny("You can't edit until the request is merged.");
}

public function authorize(PushAccessQuery $access): Response
{
$user = $this->user();
assert($user instanceof User);

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

$message = $this->route('message');
assert($message instanceof Message);

return self::authorization($user, $message, $partner, $access);
}

/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
// A caption can be cleared down to nothing, but only where images remain to hold the message up.
$message = $this->route('message');
$bodyRequired = ! ($message instanceof Message && $message->images()->exists());

return [
'body' => [$bodyRequired ? 'required' : 'nullable', 'string', 'max:'.Message::MAX_LENGTH],
];
}
}
57 changes: 57 additions & 0 deletions app/Http/Requests/UpdateOrgMessageRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\OrgRole;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;

final class UpdateOrgMessageRequest extends FormRequest
{
/**
* Only the author's own message, only within its edit window, and only where they still belong.
*/
public static function authorization(User $user, Message $message, Conversation $org): Response
{
return match (true) {
! $user->remotes_enabled || $message->event !== null || ! $message->isVisibleTo($user) || $message->conversation_id !== $org->id || ! ($org->roleOf($user) instanceof OrgRole) => Response::denyAsNotFound(),
$message->user_id !== $user->id => Response::denyAsNotFound(),
$message->voice !== null => Response::deny('Voice notes cannot be edited.'),
$message->editExpired() => Response::deny('Messages can only be edited for 3 minutes after pushing.'),
default => Response::allow(),
};
}

public function authorize(): Response
{
$user = $this->user();
assert($user instanceof User);

$org = $this->route('org');
assert($org instanceof Conversation);

$message = $this->route('message');
assert($message instanceof Message);

return self::authorization($user, $message, $org);
}

/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
// A caption can be cleared down to nothing, but only where images remain to hold the message up.
$message = $this->route('message');
$bodyRequired = ! ($message instanceof Message && $message->images()->exists());

return [
'body' => [$bodyRequired ? 'required' : 'nullable', 'string', 'max:'.Message::MAX_LENGTH],
];
}
}
17 changes: 16 additions & 1 deletion app/Models/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,37 @@
* @property-read MessageVoice|null $voice
* @property-read Collection<int, MessageReaction> $reactions
* @property-read Conversation $conversation
* @property-read CarbonInterface|null $edited_at
* @property-read CarbonInterface $created_at
* @property-read CarbonInterface $updated_at
*/
#[Visible(['id', 'user_id', 'client_id', 'body', 'reply_to_id', 'mentions', 'event', 'subject_id', 'pinned_at', 'created_at', 'user', 'subject', 'linkPreview', 'images', 'voice', 'reactions'])]
#[Visible(['id', 'user_id', 'client_id', 'body', 'reply_to_id', 'mentions', 'event', 'subject_id', 'pinned_at', 'edited_at', 'created_at', 'user', 'subject', 'linkPreview', 'images', 'voice', 'reactions'])]
final class Message extends Model
{
/** @use HasFactory<MessageFactory> */
use HasFactory;

public const int MAX_LENGTH = 2000;

/**
* How long after pushing its author may still edit a message, after which it is frozen for good.
*/
public const int EDIT_WINDOW_MINUTES = 3;

/**
* What a message is shown with in a thread: its link card, its images, its voice note, its reactions, and the
* message it replies to.
*/
public const array SHOWN_WITH = ['linkPreview', 'images', 'voice', 'reactions', 'replyTo.images', 'replyTo.voice'];

/**
* Whether the message's edit window has closed, freezing it the way the issue asked.
*/
public function editExpired(): bool
{
return $this->created_at->lt(now()->subMinutes(self::EDIT_WINDOW_MINUTES));
}

/**
* @return array<string, string>
*/
Expand All @@ -77,6 +91,7 @@ public function casts(): array
'subject_id' => 'string',
'reactions_version' => 'integer',
'pinned_at' => 'datetime',
'edited_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?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
{
public function up(): void
{
Schema::table('messages', function (Blueprint $table): void {
$table->timestamp('edited_at')->nullable()->after('pinned_at');
});
}
};
Loading