Files

95 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2025-06-25 14:09:34 +08:00
<?php
namespace App\Services\GatewayWorker;
2025-06-26 09:56:14 +08:00
use App\Enum\MessageTypeEnum;
2025-06-26 15:41:29 +08:00
use App\Models\im\ChatRoomUserModel;
use App\Models\MessageModel;
2025-06-25 16:12:51 +08:00
use App\Services\Base\BaseService;
2025-06-26 10:30:49 +08:00
use GatewayClient\Gateway;
2025-06-25 16:12:51 +08:00
class ImService extends BaseService
2025-06-25 14:09:34 +08:00
{
2025-06-26 10:21:45 +08:00
public function __construct()
{
parent::__construct();
$this->gatewayClient = GatewayClientService::getInstance()->init();
}
2025-06-25 16:12:51 +08:00
public function bindClientIdByUserId($clientId)
{
if (empty($clientId)) {
throw new \Exception('clientId不能为空');
}
GatewayClientService::getInstance()->init()->bindUser($clientId, $this->userId);
return ['绑定成功'];
}
2025-06-26 09:56:14 +08:00
2025-06-26 15:41:29 +08:00
public function getMessageByChatRoomId($chatRoomId)
{
$message = MessageModel::with([
'user',
'toUser'
])->where('chat_room_id', $chatRoomId)->get();
if (empty($message)) {
return [];
}
$result = [];
$message = $message->toArray();
foreach ($message as $v) {
$result[] = [
'userId' => $v['user_id'],
'l' => $v['user_id'] === $this->userId? 'user' : 'to_user',
'message_type' => MessageTypeEnum::from($v['type'])->description(),
'content' => $v['content'],
'nick_name' => $v['user']['nick_name'],
'avatar' => $v['user']['avatar'],
'timestamp' => $v['created_at'],
'type' => $v['user_id'] === $this->userId? 'sent' : 'received',
'user' => $v['user'],
'to_user' => $v['to_user'],
];
}
return $result;
}
public function sendMessage($data, $toUserId, $chatRoomId, $replayId, $type = MessageTypeEnum::Text->value)
2025-06-26 09:56:14 +08:00
{
2025-06-26 10:51:10 +08:00
// $uids = [1,2,3];
// $uidsC = [];
// foreach ($uids as $v) {
// $uidsC[$v] = Gateway::getClientIdByUid($v);
// }
// ds($uidsC);
2025-06-26 10:05:04 +08:00
$data['message_type'] = MessageTypeEnum::from($type)->description();
2025-06-26 10:21:45 +08:00
$this->gatewayClient->sendToUser(
2025-06-26 15:41:29 +08:00
$toUserId,
2025-06-26 10:13:19 +08:00
$this->userId,
2025-06-26 10:51:10 +08:00
$data['avatarColor'],
2025-06-26 10:51:48 +08:00
$this->userInfo['nick_name'],
2025-06-26 15:41:29 +08:00
$data['content'],
2025-06-26 09:56:14 +08:00
);
2025-06-26 15:41:29 +08:00
MessageModel::create([
'user_id' => $this->userId,
'chat_room_id' => $chatRoomId,
'to_user_id' => $toUserId,
'replay_id' => $replayId,
'type' => $type,
'content' => $data['content'],
'created_at' => time(),
]);
2025-06-26 11:02:57 +08:00
// $this->gatewayClient->broadcastMessage(
// $this->userId,
// $data['avatarColor'],
// $this->userInfo['nick_name'],
// '群发'. $data['content'],
// );
2025-06-26 09:56:14 +08:00
return ['发送成功'];
}
2025-06-25 14:09:34 +08:00
}