| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- // +----------------------------------------------------------------------
- // | Chat 消息处理类
- // +----------------------------------------------------------------------
- namespace app\services\workerman\chat;
- use app\services\workerman\Response;
- use Workerman\Connection\TcpConnection;
- class ChatHandle
- {
- protected $service;
- public function __construct(ChatService &$service)
- {
- $this->service = &$service;
- }
- /**
- * 客服登录
- */
- public function kefu_login(TcpConnection &$connection, array $res, Response $response)
- {
- if (!isset($res['data']) || !$token = $res['data']) {
- return $response->close(['msg' => '授权失败!']);
- }
- // TODO: 根据你的系统实现客服token验证
- // 示例:$kefuInfo = your_kefu_auth_service::parseToken($token);
-
- // 临时示例
- $kefuInfo = [
- 'uid' => $res['data']['uid'] ?? 1,
- 'name' => $res['data']['name'] ?? '客服',
- ];
- $connection->kefuUser = (object)$kefuInfo;
- $connection->user = (object)['uid' => $kefuInfo['uid'], 'nickname' => $kefuInfo['name'] ?? '客服'];
- $this->service->setKefuUser($connection);
- return $response->success();
- }
- /**
- * 用户登录
- */
- public function login(TcpConnection &$connection, array $res, Response $response)
- {
- if (!isset($res['data']) || !$token = $res['data']) {
- return $response->close(['msg' => '授权失败!']);
- }
- // TODO: 根据你的系统实现用户token验证
- // 示例:$authInfo = your_user_auth_service::parseToken($token);
-
- // 临时示例
- $userInfo = [
- 'uid' => $res['data']['uid'] ?? 1,
- 'nickname' => $res['data']['nickname'] ?? '用户',
- 'avatar' => $res['data']['avatar'] ?? '',
- ];
- $connection->user = (object)$userInfo;
- $this->service->setUser($connection);
- return $response->success();
- }
- /**
- * 发送消息
- */
- public function chat(TcpConnection &$connection, array $res, Response $response)
- {
- $to_uid = $res['data']['to_uid'] ?? 0;
- $msn = $res['data']['msn'] ?? '';
- $msn_type = $res['data']['type'] ?? 1; // 1=文本, 2=图片, 3=语音
- if (!$to_uid) {
- return $response->send('err_tip', ['msg' => '用户不存在']);
- }
- if ($to_uid == ($connection->user->uid ?? 0)) {
- return $response->send('err_tip', ['msg' => '不能和自己聊天']);
- }
- $uid = $connection->user->uid ?? 0;
-
- $data = [
- 'from_uid' => $uid,
- 'to_uid' => $to_uid,
- 'msn' => $msn,
- 'type' => $msn_type,
- 'add_time' => time(),
- 'nickname' => $connection->user->nickname ?? '用户',
- 'avatar' => $connection->user->avatar ?? '',
- ];
- // 给自己回复
- $response->send('chat', $data);
- // 发送给目标用户
- if (isset($this->service->user()[$to_uid])) {
- $this->response->connection($this->service->user()[$to_uid])->send('reply', $data);
- }
- }
- }
|