95 lines
2.8 KiB
PHP
95 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services\GatewayWorker;
|
|
|
|
use App\Enum\MessageTypeEnum;
|
|
use App\Models\im\ChatRoomUserModel;
|
|
use App\Models\MessageModel;
|
|
use App\Services\Base\BaseService;
|
|
use GatewayClient\Gateway;
|
|
|
|
class ImService extends BaseService
|
|
{
|
|
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
$this->gatewayClient = GatewayClientService::getInstance()->init();
|
|
}
|
|
|
|
public function bindClientIdByUserId($clientId)
|
|
{
|
|
if (empty($clientId)) {
|
|
throw new \Exception('clientId不能为空');
|
|
}
|
|
|
|
GatewayClientService::getInstance()->init()->bindUser($clientId, $this->userId);
|
|
|
|
return ['绑定成功'];
|
|
}
|
|
|
|
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)
|
|
{
|
|
// $uids = [1,2,3];
|
|
// $uidsC = [];
|
|
// foreach ($uids as $v) {
|
|
// $uidsC[$v] = Gateway::getClientIdByUid($v);
|
|
// }
|
|
// ds($uidsC);
|
|
$data['message_type'] = MessageTypeEnum::from($type)->description();
|
|
$this->gatewayClient->sendToUser(
|
|
$toUserId,
|
|
$this->userId,
|
|
$data['avatarColor'],
|
|
$this->userInfo['nick_name'],
|
|
$data['content'],
|
|
);
|
|
|
|
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(),
|
|
]);
|
|
// $this->gatewayClient->broadcastMessage(
|
|
// $this->userId,
|
|
// $data['avatarColor'],
|
|
// $this->userInfo['nick_name'],
|
|
// '群发'. $data['content'],
|
|
// );
|
|
return ['发送成功'];
|
|
}
|
|
}
|