forked from eatvio/eatvio-infra
117 lines
3.0 KiB
PHP
117 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Chat;
|
|
|
|
use App\Events\ChatMessageUpdated;
|
|
use App\Models\Chat;
|
|
use App\Models\User;
|
|
use Livewire\Component;
|
|
use Illuminate\View\View;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class MessageWindow extends Component
|
|
{
|
|
public array|Collection $messages = [];
|
|
|
|
public string $curMessage = '';
|
|
|
|
public int $curUserId;
|
|
|
|
public int|null $recipientUserId = null;
|
|
|
|
public User|null $recipientUser = null;
|
|
|
|
public string $chanId;
|
|
|
|
public User $curUser;
|
|
|
|
public function getListeners(): array
|
|
{
|
|
return [
|
|
'echo-private:direct-chat.'.$this->chanId.',ChatMessageUpdated' => 'notifyNewMessage',
|
|
'updateRecipientId',
|
|
'recipientUserIdUpdated' => '$refresh',
|
|
// 'reloadUserEcho'
|
|
];
|
|
}
|
|
|
|
public function notifyNewMessage(array $e): void
|
|
{
|
|
$message = $e['message'];
|
|
|
|
$this->messages = collect($this->messages)
|
|
->prepend($message);
|
|
}
|
|
|
|
public function updateRecipientId(int $id = null): void
|
|
{
|
|
}
|
|
|
|
public function whisperTypeing(): void
|
|
{
|
|
$this->dispatch(
|
|
'typing',
|
|
[
|
|
'chanId' => $this->chanId,
|
|
'activePeer' => $this->curUserId,
|
|
'activePeerName' => $this->curUser->name,
|
|
]
|
|
);
|
|
}
|
|
|
|
// FIXME
|
|
public function mount(int $recipientUserId = null): void
|
|
{
|
|
$this->recipientUserId = $recipientUserId;
|
|
$this->recipientUser = User::find($recipientUserId);
|
|
$this->curUser = auth()->user();
|
|
$this->curUserId = $this->curUser->id;
|
|
// $this->chanId = (int) $recipientUserId < (int) $this->curUserId
|
|
// ? $recipientUserId . "_" . $this->curUserId
|
|
// : $this->curUserId . "_" . $recipientUserId;
|
|
if (is_null($recipientUserId)) {
|
|
$this->messages = [];
|
|
} else {
|
|
$this->messages = (new Chat())->withLastTenMessages($this->curUserId, $recipientUserId)->get();
|
|
}
|
|
}
|
|
|
|
public function render(): View
|
|
{
|
|
return view('livewire.chat.message-window');
|
|
}
|
|
|
|
public function sendChatMessage(): void
|
|
{
|
|
$chatMessage = [
|
|
'data' => $this->curMessage,
|
|
'created_at' => now()->setTimezone('UTC')->format('Y-m-d H:i:s'),
|
|
'from_user_id' => $this->curUserId,
|
|
'to_user_id' => $this->recipientUserId,
|
|
];
|
|
|
|
if (mb_strlen(trim($this->curMessage)) < 1) {
|
|
return;
|
|
}
|
|
|
|
$this->saveThisMessage($chatMessage);
|
|
|
|
ChatMessageUpdated::dispatch($chatMessage);
|
|
|
|
$this->messages = collect($this->messages)
|
|
->prepend($chatMessage);
|
|
|
|
$this->reset('curMessage');
|
|
$this->curMessage = '';
|
|
}
|
|
|
|
private function saveThisMessage(array $message): void
|
|
{
|
|
$newMessage = new Chat();
|
|
$newMessage->from_user_id = $message['from_user_id'];
|
|
$newMessage->to_user_id = $message['to_user_id'];
|
|
$newMessage->data = $message['data'];
|
|
$newMessage->save();
|
|
}
|
|
}
|