hyperf-chat/app/Amqp/Consumer/ChatMessageConsumer.php

386 lines
12 KiB
PHP
Raw Normal View History

2020-11-02 22:45:37 +08:00
<?php
declare(strict_types=1);
namespace App\Amqp\Consumer;
2020-11-22 23:10:00 +08:00
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Redis\Redis;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Builder\QueueBuilder;
use PhpAmqpLib\Message\AMQPMessage;
use App\Model\User;
2020-11-29 14:44:11 +08:00
use App\Model\UsersFriend;
2020-11-21 19:53:01 +08:00
use App\Model\Chat\ChatRecord;
use App\Model\Chat\ChatRecordsCode;
use App\Model\Chat\ChatRecordsFile;
2020-11-21 22:47:21 +08:00
use App\Model\Chat\ChatRecordsInvite;
2020-11-29 14:44:11 +08:00
use App\Model\Chat\ChatRecordsForward;
use App\Service\SocketClientService;
2020-11-21 19:53:01 +08:00
use App\Service\SocketRoomService;
2020-11-02 22:45:37 +08:00
/**
2020-11-27 19:48:41 +08:00
* 消息推送消费者队列
*
2020-11-29 14:44:11 +08:00
* @Consumer(name="ConsumerChat",enable=true)
2020-11-02 22:45:37 +08:00
*/
2020-11-04 11:57:16 +08:00
class ChatMessageConsumer extends ConsumerMessage
2020-11-02 22:45:37 +08:00
{
/**
* 交换机名称
*
* @var string
*/
public $exchange = 'im.message.fanout';
/**
* 交换机类型
*
* @var string
*/
public $type = Type::FANOUT;
/**
* 路由key
*
* @var string
*/
public $routingKey = 'consumer:im:message';
2020-11-04 07:54:11 +08:00
/**
2020-11-29 14:44:11 +08:00
* @var SocketClientService
2020-11-04 07:54:11 +08:00
*/
2020-11-29 14:44:11 +08:00
private $socketClientService;
2020-11-21 19:53:01 +08:00
/**
* @var SocketRoomService
*/
private $socketRoomService;
2020-11-27 19:48:41 +08:00
/**
* 推送的消息类型推送绑定事件方法
*/
2020-11-22 23:10:00 +08:00
const EVENTS = [
2020-11-27 19:48:41 +08:00
// 聊天消息事件
2020-11-22 23:10:00 +08:00
'event_talk' => 'onConsumeTalk',
2020-11-27 19:48:41 +08:00
// 键盘输入事件
2020-11-22 23:10:00 +08:00
'event_keyboard' => 'onConsumeKeyboard',
2020-11-27 19:48:41 +08:00
// 用户在线状态事件
2020-11-22 23:10:00 +08:00
'event_online_status' => 'onConsumeOnlineStatus',
2020-11-27 19:48:41 +08:00
// 聊天消息推送事件
2020-11-22 23:10:00 +08:00
'event_revoke_talk' => 'onConsumeRevokeTalk',
2020-11-27 19:48:41 +08:00
// 好友申请相关事件
'event_friend_apply' => 'onConsumeFriendApply'
2020-11-22 23:10:00 +08:00
];
2020-11-21 19:53:01 +08:00
/**
* ChatMessageConsumer constructor.
2020-11-29 14:44:11 +08:00
* @param SocketClientService $socketClientService
2020-11-22 23:10:00 +08:00
* @param SocketRoomService $socketRoomService
2020-11-21 19:53:01 +08:00
*/
2020-11-29 14:44:11 +08:00
public function __construct(SocketClientService $socketClientService, SocketRoomService $socketRoomService)
2020-11-03 17:12:57 +08:00
{
2020-11-29 14:44:11 +08:00
$this->socketClientService = $socketClientService;
2020-11-21 19:53:01 +08:00
$this->socketRoomService = $socketRoomService;
2020-12-01 13:54:40 +08:00
$this->setQueue('queue:im_message:' . SERVER_RUN_ID);
2020-11-03 17:12:57 +08:00
}
2020-11-02 22:45:37 +08:00
/**
* 重写创建队列生成类
*
* 注释:设置自动删除队列
*
* @return QueueBuilder
*/
public function getQueueBuilder(): QueueBuilder
{
return parent::getQueueBuilder()->setAutoDelete(true);
}
/**
* 消费队列消息
*
* @param $data
* @param AMQPMessage $message
* @return string
*/
public function consumeMessage($data, AMQPMessage $message): string
2020-11-22 23:10:00 +08:00
{
if (isset($data['event'])) {
return $this->{self::EVENTS[$data['event']]}($data, $message);
}
return Result::ACK;
}
/**
* 对话聊天消息
*
* @param array $data 队列消息
* @param AMQPMessage $message
* @return string
*/
2020-12-01 13:54:40 +08:00
public function onConsumeTalk(array $data, AMQPMessage $message): string
2020-11-02 22:45:37 +08:00
{
2020-11-21 19:53:01 +08:00
$redis = container()->get(Redis::class);
2020-11-08 17:10:05 +08:00
2020-11-21 19:53:01 +08:00
//[加锁]防止消息重复消费
$lockName = sprintf('ws:message-lock:%s:%s', SERVER_RUN_ID, $data['uuid']);
if (!$redis->rawCommand('SET', $lockName, 1, 'NX', 'EX', 60)) {
return Result::ACK;
}
2020-11-02 22:45:37 +08:00
2020-11-22 23:10:00 +08:00
$source = $data['data']['source'];
2020-11-21 19:53:01 +08:00
2020-11-29 14:44:11 +08:00
$fds = $this->socketClientService->findUserFds($data['data']['sender']);
2020-11-21 19:53:01 +08:00
if ($source == 1) {// 私聊
2020-11-29 14:44:11 +08:00
$fds = array_merge($fds, $this->socketClientService->findUserFds($data['data']['receive']));
2020-11-21 19:53:01 +08:00
} else if ($source == 2) {//群聊
2020-11-22 23:10:00 +08:00
$userIds = $this->socketRoomService->getRoomMembers(strval($data['data']['receive']));
2020-11-21 19:53:01 +08:00
foreach ($userIds as $uid) {
2020-11-29 14:44:11 +08:00
$fds = array_merge($fds, $this->socketClientService->findUserFds(intval($uid)));
2020-11-03 14:07:54 +08:00
}
2020-11-21 19:53:01 +08:00
}
2020-12-01 13:54:40 +08:00
// 客户端ID去重
if (!$fds = array_unique($fds)) {
2020-11-21 19:53:01 +08:00
return Result::ACK;
}
2020-11-21 22:47:21 +08:00
/**
* @var ChatRecord
*/
2020-11-21 19:53:01 +08:00
$result = ChatRecord::leftJoin('users', 'users.id', '=', 'chat_records.user_id')
2020-11-22 23:10:00 +08:00
->where('chat_records.id', $data['data']['record_id'])
2020-11-21 19:53:01 +08:00
->first([
'chat_records.id',
'chat_records.source',
'chat_records.msg_type',
'chat_records.user_id',
'chat_records.receive_id',
'chat_records.content',
'chat_records.is_revoke',
'chat_records.created_at',
2020-11-20 19:17:11 +08:00
2020-11-21 19:53:01 +08:00
'users.nickname',
'users.avatar as avatar',
]);
2020-12-01 13:54:40 +08:00
if (!$result) return Result::ACK;
2020-11-22 23:10:00 +08:00
2020-11-21 19:53:01 +08:00
$file = [];
$code_block = [];
2020-11-21 22:47:21 +08:00
$forward = [];
$invite = [];
switch ($result->msg_type) {
case 2://文件消息
$file = ChatRecordsFile::where('record_id', $result->id)->first(['id', 'record_id', 'user_id', 'file_source', 'file_type', 'save_type', 'original_name', 'file_suffix', 'file_size', 'save_dir']);
$file = $file ? $file->toArray() : [];
2020-12-01 13:54:40 +08:00
$file && $file['file_url'] = get_media_url($file['save_dir']);
2020-11-21 22:47:21 +08:00
break;
case 3://入群消息/退群消息
$notifyInfo = ChatRecordsInvite::where('record_id', $result->id)->first([
'record_id', 'type', 'operate_user_id', 'user_ids'
]);
$userInfo = User::where('id', $notifyInfo->operate_user_id)->first(['nickname', 'id']);
$invite = [
'type' => $notifyInfo->type,
'operate_user' => ['id' => $userInfo->id, 'nickname' => $userInfo->nickname],
2020-12-01 13:54:40 +08:00
'users' => User::select('id', 'nickname')->whereIn('id', parse_ids($notifyInfo->user_ids))->get()->toArray()
2020-11-21 22:47:21 +08:00
];
2020-12-01 13:54:40 +08:00
unset($notifyInfo, $userInfo);
2020-11-21 22:47:21 +08:00
break;
case 4://会话记录消息
2020-11-27 19:48:41 +08:00
$forward = ['num' => 0, 'list' => []];
2020-11-24 23:23:12 +08:00
$forwardInfo = ChatRecordsForward::where('record_id', $result->id)->first(['records_id', 'text']);
if ($forwardInfo) {
$forward = [
'num' => substr_count($forwardInfo->records_id, ',') + 1,
'list' => json_decode($forwardInfo->text, true) ?? []
];
}
2020-11-21 22:47:21 +08:00
break;
case 5://代码块消息
$code_block = ChatRecordsCode::where('record_id', $result->id)->first(['record_id', 'code_lang', 'code']);
$code_block = $code_block ? $code_block->toArray() : [];
break;
2020-11-21 19:53:01 +08:00
}
2020-12-01 13:54:40 +08:00
$notify = [
2020-11-22 23:10:00 +08:00
'send_user' => $data['data']['sender'],
'receive_user' => $data['data']['receive'],
'source_type' => $data['data']['source'],
2020-12-01 13:54:40 +08:00
'data' => $this->formatTalkMessage([
2020-11-21 19:53:01 +08:00
'id' => $result->id,
'msg_type' => $result->msg_type,
'source' => $result->source,
'avatar' => $result->avatar,
'nickname' => $result->nickname,
"user_id" => $result->user_id,
"receive_id" => $result->receive_id,
"created_at" => $result->created_at,
"content" => $result->content,
"file" => $file,
2020-11-21 22:47:21 +08:00
"code_block" => $code_block,
'forward' => $forward,
'invite' => $invite
2020-11-21 19:53:01 +08:00
])
];
2020-11-20 19:17:11 +08:00
2020-11-29 14:44:11 +08:00
unset($result, $file, $code_block, $forward, $invite);
2020-12-01 13:54:40 +08:00
$this->socketPushNotify($fds, json_encode(['event_talk', $notify]));
2020-11-22 23:10:00 +08:00
return Result::ACK;
}
/**
* 键盘输入事件消息
*
* @param array $data 队列消息
* @param AMQPMessage $message
* @return string
*/
2020-12-01 13:54:40 +08:00
public function onConsumeKeyboard(array $data, AMQPMessage $message): string
2020-11-22 23:10:00 +08:00
{
2020-11-29 14:44:11 +08:00
$fds = $this->socketClientService->findUserFds($data['data']['receive_user']);
2020-12-01 13:54:40 +08:00
$this->socketPushNotify($fds, json_encode(['event_keyboard', $data['data']]));
2020-11-22 23:10:00 +08:00
return Result::ACK;
}
/**
* 用户上线或下线消息
*
* @param array $data 队列消息
* @param AMQPMessage $message
* @return string
*/
2020-12-01 13:54:40 +08:00
public function onConsumeOnlineStatus(array $data, AMQPMessage $message): string
2020-11-22 23:10:00 +08:00
{
2020-12-01 13:54:40 +08:00
$friends = UsersFriend::getFriendIds((int)$data['data']['user_id']);
2020-11-22 23:10:00 +08:00
$fds = [];
foreach ($friends as $friend_id) {
2020-12-01 13:54:40 +08:00
$fds = array_merge($fds, $this->socketClientService->findUserFds((int)$friend_id));
2020-11-22 23:10:00 +08:00
}
2020-12-01 13:54:40 +08:00
$this->socketPushNotify(array_unique($fds), json_encode(['event_online_status', $data['data']]));
2020-11-22 23:10:00 +08:00
return Result::ACK;
}
/**
* 撤销聊天消息
*
* @param array $data 队列消息
* @param AMQPMessage $message
* @return string
*/
2020-12-01 13:54:40 +08:00
public function onConsumeRevokeTalk(array $data, AMQPMessage $message): string
2020-11-22 23:10:00 +08:00
{
2020-11-27 19:48:41 +08:00
/** @var ChatRecord */
2020-11-22 23:10:00 +08:00
$record = ChatRecord::where('id', $data['data']['record_id'])->first(['id', 'source', 'user_id', 'receive_id']);
$fds = [];
if ($record->source == 1) {
2020-11-29 14:44:11 +08:00
$fds = array_merge($fds, $this->socketClientService->findUserFds((int)$record->user_id));
$fds = array_merge($fds, $this->socketClientService->findUserFds((int)$record->receive_id));
2020-11-22 23:10:00 +08:00
} else if ($record->source == 2) {
$userIds = $this->socketRoomService->getRoomMembers(strval($record->receive_id));
foreach ($userIds as $uid) {
2020-11-29 14:44:11 +08:00
$fds = array_merge($fds, $this->socketClientService->findUserFds((int)$uid));
2020-11-22 23:10:00 +08:00
}
}
2020-12-01 13:54:40 +08:00
$this->socketPushNotify(
array_unique($fds),
json_encode(['event_revoke_talk', [
'record_id' => $record->id,
'source' => $record->source,
'user_id' => $record->user_id,
'receive_id' => $record->receive_id,
]])
);
2020-11-03 14:07:54 +08:00
2020-11-08 17:10:05 +08:00
return Result::ACK;
2020-11-02 22:45:37 +08:00
}
2020-11-27 19:48:41 +08:00
/**
* 好友申请消息
*
2020-11-29 14:44:11 +08:00
* @param array $data 队列消息
2020-11-27 19:48:41 +08:00
* @param AMQPMessage $message
2020-11-29 14:44:11 +08:00
* @return string
2020-11-27 19:48:41 +08:00
*/
2020-12-01 13:54:40 +08:00
public function onConsumeFriendApply(array $data, AMQPMessage $message): string
2020-11-27 19:48:41 +08:00
{
2020-11-29 14:44:11 +08:00
$fds = $this->socketClientService->findUserFds($data['data']['receive']);
2020-12-01 13:54:40 +08:00
$this->socketPushNotify(array_unique($fds), json_encode(['event_friend_apply', $data['data']]));
return Result::ACK;
}
/**
* WebSocket 消息推送
*
* @param $fds
* @param $message
*/
private function socketPushNotify($fds, $message)
{
2020-11-30 22:59:49 +08:00
$server = server();
2020-11-27 19:48:41 +08:00
foreach ($fds as $fd) {
2020-12-01 13:54:40 +08:00
$server->exist($fd) && $server->push($fd, $message);
2020-11-27 19:48:41 +08:00
}
2020-12-01 13:54:40 +08:00
}
2020-11-27 19:48:41 +08:00
2020-12-01 13:54:40 +08:00
/**
* 格式化对话的消息体
*
* @param array $data 对话的消息
* @return array
*/
private function formatTalkMessage(array $data)
{
$message = [
"id" => 0,//消息记录ID
"source" => 1,//消息来源[1:好友私信;2:群聊]
"msg_type" => 1,
"user_id" => 0,//发送者用户ID
"receive_id" => 0,//接收者ID[好友ID或群ID]
"content" => '',//文本消息
"is_revoke" => 0,//消息是否撤销
// 发送消息人的信息
"nickname" => "",
"avatar" => "",
// 不同的消息类型
"file" => [],
"code_block" => [],
"forward" => [],
"invite" => [],
// 消息创建时间
"created_at" => "",
];
return array_merge($message, array_intersect_key($data, $message));
2020-11-27 19:48:41 +08:00
}
2020-11-02 22:45:37 +08:00
}