75 lines
2.8 KiB
PHP
75 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Livewire;
|
|
|
|
use Livewire\Component;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Namu\WireChat\Models\Participant;
|
|
|
|
class UnreadIndicator extends Component
|
|
{
|
|
use \App\Traits\ListensToProfileChats;
|
|
|
|
public int $unreadCount = 0;
|
|
|
|
public function getListeners(): array
|
|
{
|
|
// Chat events of every profile of the logged-in user, not only the active one: the keys
|
|
// must stay the same after a profile switch (see ListensToProfileChats).
|
|
return array_merge([
|
|
'conversations-updated' => 'updateUnreadCount',
|
|
'refresh' => 'updateUnreadCount', // Listen to generic refresh events
|
|
'refreshList' => 'updateUnreadCount', // Listen to chat list refresh events
|
|
], $this->profileChatListeners('updateUnreadCount'));
|
|
}
|
|
|
|
public function mount(): void
|
|
{
|
|
$this->updateUnreadCount();
|
|
}
|
|
|
|
public function updateUnreadCount(): void
|
|
{
|
|
// Get the active guard from session
|
|
$guard = session('active_guard', 'web');
|
|
$user = auth($guard)->user();
|
|
|
|
if ($user) {
|
|
$participantsTable = (new Participant)->getTable();
|
|
$this->unreadCount = DB::table($participantsTable . ' as p')
|
|
->join('wirechat_conversations as c', 'p.conversation_id', '=', 'c.id')
|
|
->where('p.participantable_id', $user->id)
|
|
->where('p.participantable_type', $user->getMorphClass())
|
|
->whereNull('p.deleted_at')
|
|
->where(function ($q) {
|
|
$q->whereNull('p.conversation_read_at')
|
|
->orWhereColumn('c.updated_at', '>', 'p.conversation_read_at');
|
|
})
|
|
->whereExists(function ($q) use ($user) {
|
|
// Only count if there's a message NOT sent by this user that is unread
|
|
$q->select(DB::raw(1))
|
|
->from('wirechat_messages as m')
|
|
->whereColumn('m.conversation_id', 'p.conversation_id')
|
|
->whereNull('m.deleted_at')
|
|
->where(function ($q2) use ($user) {
|
|
$q2->where('m.sendable_id', '!=', $user->id)
|
|
->orWhere('m.sendable_type', '!=', $user->getMorphClass());
|
|
})
|
|
->where(function ($q3) {
|
|
$q3->whereNull('p.conversation_read_at')
|
|
->orWhereColumn('m.created_at', '>', 'p.conversation_read_at');
|
|
});
|
|
})
|
|
->count();
|
|
|
|
|
|
// Dispatch browser event to notify JS when unread count changes
|
|
$this->dispatch('unread-count-updated', count: $this->unreadCount);
|
|
}
|
|
}
|
|
|
|
public function render()
|
|
{
|
|
return view('livewire.unread-indicator');
|
|
}
|
|
} |