| | |
| | | |
| | | use \GatewayWorker\Lib\Gateway; |
| | | use app\api\model\plus\business\chat\Chat as BusinessChatModel; |
| | | use app\api\model\plus\business\chat\Participant as BusinessParticipantModel; |
| | | use Workerman\Lib\Timer; |
| | | use Workerman\Worker; |
| | | use think\worker\Application; |
| | |
| | | { |
| | | // 向当前client_id发送数据 |
| | | $data['client_id'] = $client_id; |
| | | $data['type'] = 'init'; |
| | | $data['type'] = 'init';//心跳 |
| | | Gateway::sendToClient($client_id, json_encode($data)); |
| | | } |
| | | |
| | |
| | | public static function onMessage($client_id, $message) |
| | | { |
| | | $data = json_decode($message, 1); |
| | | $to = 'user_' . $data['to_user_id']; |
| | | $to = !empty($data['to_user_id']) ? 'user_' . $data['to_user_id'] : 0; |
| | | $from_id = 'user_' . $data['user_id']; |
| | | |
| | | if ($data['type'] !== 'ping' && $data['type'] !== 'close') {//正常发送消息 |
| | | if (Gateway::isUidOnline($to)) { |
| | | $data['time'] = date('Y-m-d H:i:s'); |
| | | Gateway::sendToUid($to, json_encode($data)); |
| | | } |
| | | |
| | | // 保存消息到数据库 |
| | | $Chat = new BusinessChatModel; |
| | | $Chat->addBusinessMessage($data, ['user_id' => $data['user_id']]); |
| | | if ($data['type'] == 'bind') { |
| | | // 绑定client_id和user_id |
| | | Gateway::bindUid($client_id, $from_id); |
| | | |
| | | } else if ($data['type'] == 'ping') { |
| | | //心跳 |
| | | $data['Online'] = $to && Gateway::isUidOnline($to) ? 'on' : 'off'; |
| | | $data['Online'] = $to && Gateway::isUidOnline($to) ? 'off' : 'on'; |
| | | Gateway::sendToUid($from_id, json_encode($data)); |
| | | } else if ($data['type'] == 'close') { |
| | | //断开链接 |
| | | Gateway::unbindUid($client_id, $from_id); |
| | | } else if ($data['type'] == 'read') { |
| | | // 消息已读处理 |
| | | $chatModel = new BusinessChatModel(); |
| | | $chatModel->markAsRead($data['chat_id'], $data['user_id']); |
| | | |
| | | // 更新参与者最后阅读时间 |
| | | $participantModel = new BusinessParticipantModel(); |
| | | $participantModel->updateLastReadTime($data['conversation_id'], $data['user_id']); |
| | | if ($to && Gateway::isUidOnline($to)) { |
| | | Gateway::sendToUid($to, json_encode($data)); |
| | | } |
| | | } else if ($data['type'] !== 'ping' && $data['type'] !== 'close') {//正常发送消息 |
| | | // 绑定client_id和user_id |
| | | Gateway::bindUid($client_id, $from_id); |
| | | // 保存消息到数据库 |
| | | $Chat = new BusinessChatModel; |
| | | $Chat->sendMessage($data['conversation_id'], $data['user_id'], $data['content'], 0, $data['app_id']); |
| | | // 检查接收方是否在线 |
| | | if ($to && Gateway::isUidOnline($to)) { |
| | | $data['send_time'] = time(); |
| | | $data['chat_id']=$Chat->chat_id; |
| | | Gateway::sendToUid($to, json_encode($data)); |
| | | } |
| | | } |
| | | } |
| | | |