优化代码

main
gzydong 2021-07-10 00:18:40 +08:00
parent e495847a73
commit 1e04fdc360
8 changed files with 297 additions and 248 deletions

View File

@ -10,21 +10,19 @@
namespace App\Controller\Api\V1; namespace App\Controller\Api\V1;
use App\Cache\SocketRoom;
use App\Constants\TalkMode; use App\Constants\TalkMode;
use App\Service\GroupNoticeService;
use App\Service\TalkListService;
use App\Service\UserService; use App\Service\UserService;
use App\Support\MessageProducer;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping; use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware; use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\JWTAuthMiddleware; use App\Middleware\JWTAuthMiddleware;
use App\Model\TalkList;
use App\Model\Group\Group; use App\Model\Group\Group;
use App\Model\Group\GroupMember; use App\Model\Group\GroupMember;
use App\Model\Group\GroupNotice; use App\Model\Group\GroupNotice;
use App\Service\GroupService; use App\Service\GroupService;
use App\Constants\TalkMessageEvent;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
/** /**
@ -56,36 +54,16 @@ class GroupController extends CController
'uids' => 'required|ids' 'uids' => 'required|ids'
]); ]);
$friend_ids = parse_ids($params['uids']); [$isTrue, $group] = $this->groupService->create($this->uid(), [
$user_id = $this->uid();
[$isTrue, $data] = $this->groupService->create($user_id, [
'name' => $params['group_name'], 'name' => $params['group_name'],
'avatar' => $params['avatar'] ?? '', 'avatar' => $params['avatar'] ?? '',
'profile' => $params['group_profile'] ?? '' 'profile' => $params['group_profile'] ?? ''
], $friend_ids); ], parse_ids($params['uids']));
if (!$isTrue) { if (!$isTrue) return $this->response->fail('创建群聊失败,请稍后再试!');
return $this->response->fail('创建群聊失败,请稍后再试!');
}
// 加入聊天室
$friend_ids[] = $user_id;
foreach ($friend_ids as $uid) {
SocketRoom::getInstance()->addRoomMember(strval($data['group_id']), $uid);
}
MessageProducer::publish(
MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => (int)$data['group_id'],
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => (int)$data['record_id']
])
);
return $this->response->success([ return $this->response->success([
'group_id' => $data['group_id'] 'group_id' => $group->id
]); ]);
} }
@ -107,10 +85,6 @@ class GroupController extends CController
return $this->response->fail('群组解散失败!'); return $this->response->fail('群组解散失败!');
} }
SocketRoom::getInstance()->delRoom($params['group_id']);
// ... TODO 推送群消息(预留)
return $this->response->success([], '群组解散成功...'); return $this->response->success([], '群组解散成功...');
} }
@ -128,28 +102,11 @@ class GroupController extends CController
'uids' => 'required|ids' 'uids' => 'required|ids'
]); ]);
$uids = parse_ids($params['uids']); $isTrue = $this->groupService->invite($this->uid(), $params['group_id'], parse_ids($params['uids']));
$user_id = $this->uid();
[$isTrue, $record_id] = $this->groupService->invite($user_id, $params['group_id'], $uids);
if (!$isTrue) { if (!$isTrue) {
return $this->response->fail('邀请好友加入群聊失败!'); return $this->response->fail('邀请好友加入群聊失败!');
} }
// 加入聊天室
foreach ($uids as $uid) {
SocketRoom::getInstance()->addRoomMember($params['group_id'], $uid);
}
MessageProducer::publish(
MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => (int)$params['group_id'],
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $record_id
])
);
return $this->response->success([], '好友已成功加入群聊...'); return $this->response->success([], '好友已成功加入群聊...');
} }
@ -166,24 +123,10 @@ class GroupController extends CController
'group_id' => 'required|integer' 'group_id' => 'required|integer'
]); ]);
$user_id = $this->uid(); if (!$this->groupService->quit($this->uid(), $params['group_id'])) {
[$isTrue, $record_id] = $this->groupService->quit($user_id, $params['group_id']);
if (!$isTrue) {
return $this->response->fail('退出群组失败!'); return $this->response->fail('退出群组失败!');
} }
// 移出聊天室
SocketRoom::getInstance()->delRoomMember($params['group_id'], $user_id);
MessageProducer::publish(
MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => (int)$params['group_id'],
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $record_id
])
);
return $this->response->success([], '已成功退出群组...'); return $this->response->success([], '已成功退出群组...');
} }
@ -203,15 +146,7 @@ class GroupController extends CController
'avatar' => 'present|url' 'avatar' => 'present|url'
]); ]);
$result = Group::where('id', $params['group_id'])->where('creator_id', $this->uid())->update([ return $this->groupService->update($params['group_id'], $this->uid(), $params)
'group_name' => $params['group_name'],
'profile' => $params['profile'],
'avatar' => $params['avatar']
]);
// ... TODO 推送消息通知(预留)
return $result
? $this->response->success([], '群组信息修改成功...') ? $this->response->success([], '群组信息修改成功...')
: $this->response->fail('群组信息修改失败!'); : $this->response->fail('群组信息修改失败!');
} }
@ -237,25 +172,11 @@ class GroupController extends CController
return $this->response->fail('群聊用户移除失败!'); return $this->response->fail('群聊用户移除失败!');
} }
[$isTrue, $record_id] = $this->groupService->removeMember($params['group_id'], $user_id, $params['members_ids']); $isTrue = $this->groupService->removeMember($params['group_id'], $user_id, $params['members_ids']);
if (!$isTrue) { if (!$isTrue) {
return $this->response->fail('群聊用户移除失败!'); return $this->response->fail('群聊用户移除失败!');
} }
// 移出聊天室
foreach ($params['members_ids'] as $uid) {
SocketRoom::getInstance()->delRoomMember($params['group_id'], strval($uid));
}
MessageProducer::publish(
MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => (int)$params['group_id'],
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $record_id
])
);
return $this->response->success([], '已成功退出群组...'); return $this->response->success([], '已成功退出群组...');
} }
@ -265,7 +186,7 @@ class GroupController extends CController
* *
* @return ResponseInterface * @return ResponseInterface
*/ */
public function detail() public function detail(TalkListService $service)
{ {
$group_id = $this->request->input('group_id', 0); $group_id = $this->request->input('group_id', 0);
$user_id = $this->uid(); $user_id = $this->uid();
@ -281,14 +202,9 @@ class GroupController extends CController
'users.nickname' 'users.nickname'
]); ]);
if (!$groupInfo) { if (!$groupInfo) return $this->response->success();
return $this->response->success();
}
$notice = GroupNotice::where('group_id', $group_id) $notice = GroupNotice::where('group_id', $group_id)->where('is_delete', 0)->orderBy('id', 'desc')->first(['title', 'content']);
->where('is_delete', 0)
->orderBy('id', 'desc')
->first(['title', 'content']);
return $this->response->success([ return $this->response->success([
'group_id' => $groupInfo->id, 'group_id' => $groupInfo->id,
@ -299,7 +215,7 @@ class GroupController extends CController
'is_manager' => $groupInfo->creator_id == $user_id, 'is_manager' => $groupInfo->creator_id == $user_id,
'manager_nickname' => $groupInfo->nickname, 'manager_nickname' => $groupInfo->nickname,
'visit_card' => GroupMember::visitCard($user_id, $group_id), 'visit_card' => GroupMember::visitCard($user_id, $group_id),
'is_disturb' => (int)TalkList::where('user_id', $user_id)->where('receiver_id', $group_id)->where('talk_type', TalkMode::GROUP_CHAT)->value('is_disturb'), 'is_disturb' => (int)$service->isDisturb($user_id, $group_id, TalkMode::GROUP_CHAT),
'notice' => $notice ? $notice->toArray() : [] 'notice' => $notice ? $notice->toArray() : []
]); ]);
} }
@ -318,9 +234,7 @@ class GroupController extends CController
'visit_card' => 'required|max:20' 'visit_card' => 'required|max:20'
]); ]);
$isTrue = GroupMember::where('group_id', $params['group_id']) $isTrue = $this->groupService->updateMemberCard($params['group_id'], $this->uid(), $params['visit_card']);
->where('user_id', $this->uid())
->update(['user_card' => $params['visit_card']]);
return $isTrue return $isTrue
? $this->response->success([], '群名片修改成功...') ? $this->response->success([], '群名片修改成功...')
@ -359,7 +273,7 @@ class GroupController extends CController
public function getGroups() public function getGroups()
{ {
return $this->response->success( return $this->response->success(
$this->groupService->getGroups($this->uid()) $this->groupService->getUserGroups($this->uid())
); );
} }
@ -404,7 +318,7 @@ class GroupController extends CController
* *
* @return ResponseInterface * @return ResponseInterface
*/ */
public function getGroupNotice() public function getGroupNotice(GroupNoticeService $service)
{ {
$user_id = $this->uid(); $user_id = $this->uid();
$group_id = $this->request->input('group_id', 0); $group_id = $this->request->input('group_id', 0);
@ -414,28 +328,7 @@ class GroupController extends CController
return $this->response->fail('非管理员禁止操作!'); return $this->response->fail('非管理员禁止操作!');
} }
$rows = GroupNotice::leftJoin('users', 'users.id', '=', 'group_notice.creator_id') return $this->response->success($service->lists($group_id));
->where([
['group_notice.group_id', '=', $group_id],
['group_notice.is_delete', '=', 0]
])
->orderBy('group_notice.is_top', 'desc')
->orderBy('group_notice.updated_at', 'desc')
->get([
'group_notice.id',
'group_notice.creator_id',
'group_notice.title',
'group_notice.content',
'group_notice.is_top',
'group_notice.is_confirm',
'group_notice.confirm_users',
'group_notice.created_at',
'group_notice.updated_at',
'users.avatar',
'users.nickname',
])->toArray();
return $this->response->success($rows);
} }
/** /**
@ -444,7 +337,7 @@ class GroupController extends CController
* *
* @return ResponseInterface * @return ResponseInterface
*/ */
public function editNotice() public function editNotice(GroupNoticeService $service)
{ {
$params = $this->request->inputs(['group_id', 'notice_id', 'title', 'content', 'is_top', 'is_confirm']); $params = $this->request->inputs(['group_id', 'notice_id', 'title', 'content', 'is_top', 'is_confirm']);
$this->validate($params, [ $this->validate($params, [
@ -465,34 +358,14 @@ class GroupController extends CController
// 判断是否是新增数据 // 判断是否是新增数据
if (empty($params['notice_id'])) { if (empty($params['notice_id'])) {
$result = GroupNotice::create([ if (!$service->create($user_id, $params)) {
'group_id' => $params['group_id'],
'creator_id' => $user_id,
'title' => $params['title'],
'content' => $params['content'],
'is_top' => $params['is_top'],
'is_confirm' => $params['is_confirm'],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
if (!$result) {
return $this->response->fail('添加群公告信息失败!'); return $this->response->fail('添加群公告信息失败!');
} }
// ... TODO 推送群消息(预留)
return $this->response->success([], '添加群公告信息成功...'); return $this->response->success([], '添加群公告信息成功...');
} }
$result = GroupNotice::where('id', $params['notice_id'])->update([ return $service->update($params)
'title' => $params['title'],
'content' => $params['content'],
'is_top' => $params['is_top'],
'updated_at' => date('Y-m-d H:i:s')
]);
return $result
? $this->response->success([], '修改群公告信息成功...') ? $this->response->success([], '修改群公告信息成功...')
: $this->response->fail('修改群公告信息失败!'); : $this->response->fail('修改群公告信息失败!');
} }
@ -503,7 +376,7 @@ class GroupController extends CController
* *
* @return ResponseInterface * @return ResponseInterface
*/ */
public function deleteNotice() public function deleteNotice(GroupNoticeService $service)
{ {
$params = $this->request->inputs(['group_id', 'notice_id']); $params = $this->request->inputs(['group_id', 'notice_id']);
$this->validate($params, [ $this->validate($params, [
@ -511,21 +384,13 @@ class GroupController extends CController
'notice_id' => 'required|integer' 'notice_id' => 'required|integer'
]); ]);
$user_id = $this->uid(); try {
$isTrue = $service->delete($params['notice_id'], $this->uid());
// 判断用户是否是管理员 } catch (\Exception $e) {
if (!Group::isManager($user_id, $params['group_id'])) { return $this->response->fail($e->getMessage());
return $this->response->fail('非法操作!');
} }
$result = GroupNotice::where('id', $params['notice_id']) return $isTrue
->where('group_id', $params['group_id'])
->update([
'is_delete' => 1,
'deleted_at' => date('Y-m-d H:i:s')
]);
return $result
? $this->response->success([], '公告删除成功...') ? $this->response->success([], '公告删除成功...')
: $this->response->fail('公告删除失败!'); : $this->response->fail('公告删除失败!');
} }

View File

@ -27,8 +27,8 @@ class UsersEmoticon extends BaseModel
]; ];
/** /**
* @param string $value * @param $value
* @return string * @return false|string[]
*/ */
public function getEmoticonIdsAttribute($value) public function getEmoticonIdsAttribute($value)
{ {

View File

@ -0,0 +1,91 @@
<?php
namespace App\Service;
use _HumbugBox39a196d4601e\Nette\Neon\Exception;
use App\Model\Group\Group;
use App\Model\Group\GroupNotice;
class GroupNoticeService
{
public function create(int $user_id, array $params)
{
return GroupNotice::create([
'group_id' => $params['group_id'],
'creator_id' => $user_id,
'title' => $params['title'],
'content' => $params['content'],
'is_top' => $params['is_top'],
'is_confirm' => $params['is_confirm'],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
public function update(array $params)
{
return GroupNotice::where('id', $params['notice_id'])->update([
'title' => $params['title'],
'content' => $params['content'],
'is_top' => $params['is_top'],
'updated_at' => date('Y-m-d H:i:s')
]);
}
/**
* 删除群公告
*
* @param int $notice_id 公告ID
* @param int $user_id 用户ID
* @return bool
* @throws Exception
*/
public function delete(int $notice_id, int $user_id)
{
$notice = GroupNotice::where('id', $notice_id)->first();
if (!$notice) {
return false;
}
// 判断用户是否是管理员
if (!Group::isManager($user_id, $notice->group_id)) {
throw new Exception('非管理员,无法进行操作!', 403);
}
$notice->is_delete = 1;
$notice->deleted_at = date('Y-m-d H:i:s');
$notice->save();
return true;
}
/**
* 获取群公告列表
*
* @param int $group_id 群ID
* @return array
*/
public function lists(int $group_id)
{
return GroupNotice::leftJoin('users', 'users.id', '=', 'group_notice.creator_id')
->where([
['group_notice.group_id', '=', $group_id],
['group_notice.is_delete', '=', 0]
])
->orderBy('group_notice.is_top', 'desc')
->orderBy('group_notice.updated_at', 'desc')
->get([
'group_notice.id',
'group_notice.creator_id',
'group_notice.title',
'group_notice.content',
'group_notice.is_top',
'group_notice.is_confirm',
'group_notice.confirm_users',
'group_notice.created_at',
'group_notice.updated_at',
'users.avatar',
'users.nickname',
])->toArray();
}
}

View File

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\Cache\LastMessage; use App\Cache\LastMessage;
use App\Cache\SocketRoom;
use App\Constants\TalkMessageEvent;
use App\Constants\TalkMessageType; use App\Constants\TalkMessageType;
use App\Constants\TalkMode; use App\Constants\TalkMode;
use App\Model\Talk\TalkRecords; use App\Model\Talk\TalkRecords;
@ -11,6 +13,7 @@ use App\Model\Talk\TalkRecordsInvite;
use App\Model\Group\Group; use App\Model\Group\Group;
use App\Model\Group\GroupMember; use App\Model\Group\GroupMember;
use App\Model\Talk\TalkList; use App\Model\Talk\TalkList;
use App\Support\MessageProducer;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
use Exception; use Exception;
@ -21,43 +24,6 @@ use Exception;
*/ */
class GroupService extends BaseService class GroupService extends BaseService
{ {
/**
* 获取用户所在的群聊
*
* @param int $user_id 用户ID
* @return array
*/
public function getGroups(int $user_id): array
{
$items = GroupMember::join('group', 'group.id', '=', 'group_member.group_id')
->where([
['group_member.user_id', '=', $user_id],
['group_member.is_quit', '=', 0]
])
->orderBy('id', 'desc')
->get([
'group.id',
'group.group_name',
'group.avatar',
'group.profile',
'group_member.leader',
])->toArray();
$list = [];
if ($items) {
$list = TalkList::query()->where('user_id', $user_id)
->where('talk_type', TalkMode::GROUP_CHAT)
->whereIn('receiver_id', array_column($items, 'id'))
->get(['receiver_id', 'is_disturb'])->keyBy('receiver_id')->toArray();
}
foreach ($items as $key => $item) {
$items[$key]['is_disturb'] = isset($list[$item['id']]) ? $list[$item['id']]['is_disturb'] : 0;
}
return $items;
}
/** /**
* 创建群组 * 创建群组
* *
@ -75,7 +41,7 @@ class GroupService extends BaseService
Db::beginTransaction(); Db::beginTransaction();
try { try {
$insRes = Group::create([ $group = Group::create([
'creator_id' => $user_id, 'creator_id' => $user_id,
'group_name' => $group_info['name'], 'group_name' => $group_info['name'],
'avatar' => $group_info['avatar'], 'avatar' => $group_info['avatar'],
@ -89,7 +55,7 @@ class GroupService extends BaseService
foreach ($friend_ids as $friend_id) { foreach ($friend_ids as $friend_id) {
$groupMember[] = [ $groupMember[] = [
'group_id' => $insRes->id, 'group_id' => $group->id,
'user_id' => $friend_id, 'user_id' => $friend_id,
'leader' => $user_id == $friend_id ? 2 : 0, 'leader' => $user_id == $friend_id ? 2 : 0,
'created_at' => date('Y-m-d H:i:s'), 'created_at' => date('Y-m-d H:i:s'),
@ -98,7 +64,7 @@ class GroupService extends BaseService
$chatList[] = [ $chatList[] = [
'talk_type' => TalkMode::GROUP_CHAT, 'talk_type' => TalkMode::GROUP_CHAT,
'user_id' => $friend_id, 'user_id' => $friend_id,
'receiver_id' => $insRes->id, 'receiver_id' => $group->id,
'created_at' => date('Y-m-d H:i:s'), 'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s') 'updated_at' => date('Y-m-d H:i:s')
]; ];
@ -115,7 +81,7 @@ class GroupService extends BaseService
$result = TalkRecords::create([ $result = TalkRecords::create([
'talk_type' => TalkMode::GROUP_CHAT, 'talk_type' => TalkMode::GROUP_CHAT,
'user_id' => 0, 'user_id' => 0,
'receiver_id' => $insRes->id, 'receiver_id' => $group->id,
'msg_type' => TalkMessageType::GROUP_INVITE_MESSAGE, 'msg_type' => TalkMessageType::GROUP_INVITE_MESSAGE,
'created_at' => date('Y-m-d H:i:s'), 'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s') 'updated_at' => date('Y-m-d H:i:s')
@ -131,15 +97,42 @@ class GroupService extends BaseService
Db::commit(); Db::commit();
} catch (Exception $e) { } catch (Exception $e) {
Db::rollBack(); Db::rollBack();
return [false, 0]; return [false, null];
} }
LastMessage::getInstance()->save(TalkMode::GROUP_CHAT, $user_id, $insRes->id, [ LastMessage::getInstance()->save(TalkMode::GROUP_CHAT, $user_id, $group->id, [
'text' => '[入群通知]', 'text' => '[入群通知]',
'created_at' => date('Y-m-d H:i:s') 'created_at' => date('Y-m-d H:i:s')
]); ]);
return [true, ['record_id' => $result->id, 'group_id' => $insRes->id]]; // 加入聊天室
foreach ($friend_ids as $uid) {
SocketRoom::getInstance()->addRoomMember(strval($data['group_id']), $uid);
}
MessageProducer::publish(MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => $group->id,
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => (int)$data['record_id']
]));
return [true, $group];
}
/**
* @param int $group_id
* @param int $user_id
* @param array $params
* @return bool
*/
public function update(int $group_id, int $user_id, array $params)
{
return (bool)Group::where('id', $group_id)->where('creator_id', $user_id)->update([
'group_name' => $params['group_name'] ?? '',
'profile' => $params['profile'] ?? '',
'avatar' => $params['avatar'] ?? ''
]);
} }
/** /**
@ -156,6 +149,7 @@ class GroupService extends BaseService
return false; return false;
} }
try {
DB::transaction(function () use ($group_id, $user_id) { DB::transaction(function () use ($group_id, $user_id) {
Group::where('id', $group_id)->where('creator_id', $user_id)->update([ Group::where('id', $group_id)->where('creator_id', $user_id)->update([
'is_dismiss' => 1, 'is_dismiss' => 1,
@ -167,6 +161,13 @@ class GroupService extends BaseService
'deleted_at' => date('Y-m-d H:i:s'), 'deleted_at' => date('Y-m-d H:i:s'),
]); ]);
}); });
} catch (\Exception $e) {
return false;
}
SocketRoom::getInstance()->delRoom($group_id);
// ... TODO 推送群消息(预留)
return true; return true;
} }
@ -177,17 +178,17 @@ class GroupService extends BaseService
* @param int $user_id 用户ID * @param int $user_id 用户ID
* @param int $group_id 聊天群ID * @param int $group_id 聊天群ID
* @param array $friend_ids 被邀请的用户ID * @param array $friend_ids 被邀请的用户ID
* @return array * @return bool
*/ */
public function invite(int $user_id, int $group_id, $friend_ids = []) public function invite(int $user_id, int $group_id, $friend_ids = [])
{ {
if (!$friend_ids) return [false, 0]; if (!$friend_ids) return false;
$info = GroupMember::where('group_id', $group_id)->where('user_id', $user_id)->first(['id', 'is_quit']); $info = GroupMember::where('group_id', $group_id)->where('user_id', $user_id)->first(['id', 'is_quit']);
// 判断主动邀请方是否属于聊天群成员 // 判断主动邀请方是否属于聊天群成员
if (!$info && $info->is_quit == 1) { if (!$info && $info->is_quit == 1) {
return [false, 0]; return false;
} }
$updateArr = $insertArr = $updateArr1 = $insertArr1 = []; $updateArr = $insertArr = $updateArr1 = $insertArr1 = [];
@ -269,7 +270,7 @@ class GroupService extends BaseService
Db::commit(); Db::commit();
} catch (Exception $e) { } catch (Exception $e) {
Db::rollBack(); Db::rollBack();
return [false, 0]; return false;
} }
LastMessage::getInstance()->save(TalkMode::GROUP_CHAT, $user_id, $group_id, [ LastMessage::getInstance()->save(TalkMode::GROUP_CHAT, $user_id, $group_id, [
@ -277,7 +278,19 @@ class GroupService extends BaseService
'created_at' => date('Y-m-d H:i:s') 'created_at' => date('Y-m-d H:i:s')
]); ]);
return [true, $result->id]; // 加入聊天室
foreach ($friend_ids as $value) {
SocketRoom::getInstance()->addRoomMember(strval($group_id), strval($value));
}
MessageProducer::publish(MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => $group_id,
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $result->id
]));
return true;
} }
/** /**
@ -285,13 +298,13 @@ class GroupService extends BaseService
* *
* @param int $user_id 用户ID * @param int $user_id 用户ID
* @param int $group_id 群组ID * @param int $group_id 群组ID
* @return array * @return bool
*/ */
public function quit(int $user_id, int $group_id) public function quit(int $user_id, int $group_id)
{ {
// 判断是否属于管理员 // 判断是否属于管理员
if (Group::isManager($user_id, $group_id)) { if (Group::isManager($user_id, $group_id)) {
return [false, 0]; return false;
} }
Db::beginTransaction(); Db::beginTransaction();
@ -301,9 +314,7 @@ class GroupService extends BaseService
'deleted_at' => date('Y-m-d H:i:s'), 'deleted_at' => date('Y-m-d H:i:s'),
]); ]);
if ($count == 0) { if ($count == 0) throw new Exception('更新记录失败...');
throw new Exception('更新记录失败...');
}
$result = TalkRecords::create([ $result = TalkRecords::create([
'talk_type' => TalkMode::GROUP_CHAT, 'talk_type' => TalkMode::GROUP_CHAT,
@ -315,8 +326,6 @@ class GroupService extends BaseService
'updated_at' => date('Y-m-d H:i:s') 'updated_at' => date('Y-m-d H:i:s')
]); ]);
$record_id = $result->id;
TalkRecordsInvite::create([ TalkRecordsInvite::create([
'record_id' => $result->id, 'record_id' => $result->id,
'type' => 2, 'type' => 2,
@ -328,17 +337,25 @@ class GroupService extends BaseService
['talk_type', '=', TalkMode::GROUP_CHAT], ['talk_type', '=', TalkMode::GROUP_CHAT],
['user_id', '=', $user_id], ['user_id', '=', $user_id],
['receiver_id', '=', $group_id], ['receiver_id', '=', $group_id],
])->update([ ])->update(['is_delete' => 1]);
'is_delete' => 1
]);
Db::commit(); Db::commit();
} catch (Exception $e) { } catch (Exception $e) {
Db::rollBack(); Db::rollBack();
return [false, 0]; return false;
} }
return [true, $record_id]; // 移出聊天室
SocketRoom::getInstance()->delRoomMember(strval($group_id), strval($user_id));
MessageProducer::publish(MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => (int)$params['group_id'],
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $result->id
]));
return true;
} }
/** /**
@ -347,12 +364,12 @@ class GroupService extends BaseService
* @param int $group_id 群ID * @param int $group_id 群ID
* @param int $user_id 操作用户ID * @param int $user_id 操作用户ID
* @param array $member_ids 群成员ID * @param array $member_ids 群成员ID
* @return array * @return bool
*/ */
public function removeMember(int $group_id, int $user_id, array $member_ids) public function removeMember(int $group_id, int $user_id, array $member_ids)
{ {
if (!Group::isManager($user_id, $group_id)) { if (!Group::isManager($user_id, $group_id)) {
return [false, 0]; return false;
} }
Db::beginTransaction(); Db::beginTransaction();
@ -362,9 +379,7 @@ class GroupService extends BaseService
'deleted_at' => date('Y-m-d H:i:s'), 'deleted_at' => date('Y-m-d H:i:s'),
]); ]);
if ($count == 0) { if ($count == 0) throw new Exception('更新记录失败...');
throw new Exception('更新记录失败...');
}
$result = TalkRecords::create([ $result = TalkRecords::create([
'talk_type' => TalkMode::GROUP_CHAT, 'talk_type' => TalkMode::GROUP_CHAT,
@ -390,9 +405,71 @@ class GroupService extends BaseService
Db::commit(); Db::commit();
} catch (Exception $e) { } catch (Exception $e) {
Db::rollBack(); Db::rollBack();
return [false, 0]; return false;
} }
return [true, $result->id]; // 移出聊天室
foreach ($member_ids as $uid) {
SocketRoom::getInstance()->delRoomMember(strval($group_id), strval($uid));
}
MessageProducer::publish(MessageProducer::create(TalkMessageEvent::EVENT_TALK, [
'sender_id' => $user_id,
'receiver_id' => $group_id,
'talk_type' => TalkMode::GROUP_CHAT,
'record_id' => $result->id
]));
return true;
}
/**
* 更新用户群名片
*
* @param int $group_id 群ID
* @param int $user_id 用户ID
* @param string $user_card 用户名片
* @return bool
*/
public function updateMemberCard(int $group_id, int $user_id, string $user_card)
{
return (bool)GroupMember::where('group_id', $group_id)->where('user_id', $user_id)->update(['user_card' => $user_card]);
}
/**
* 获取用户所在的群聊
*
* @param int $user_id 用户ID
* @return array
*/
public function getUserGroups(int $user_id): array
{
$fields = [
'group.id',
'group.group_name',
'group.avatar',
'group.profile',
'group_member.leader',
];
$items = GroupMember::join('group', 'group.id', '=', 'group_member.group_id')
->where([
['group_member.user_id', '=', $user_id],
['group_member.is_quit', '=', 0]
])->orderBy('id', 'desc')->get($fields)->toArray();
$list = [];
if ($items) {
$list = TalkList::query()->where('user_id', $user_id)
->where('talk_type', TalkMode::GROUP_CHAT)
->whereIn('receiver_id', array_column($items, 'id'))
->get(['receiver_id', 'is_disturb'])->keyBy('receiver_id')->toArray();
}
foreach ($items as $key => $item) {
$items[$key]['is_disturb'] = isset($list[$item['id']]) ? $list[$item['id']]['is_disturb'] : 0;
}
return $items;
} }
} }

View File

@ -1,9 +1,7 @@
<?php <?php
namespace App\Service; namespace App\Service;
class PushMessageService class PushMessageService
{ {
public function loginMessage(int $user_id, array $params) public function loginMessage(int $user_id, array $params)

View File

@ -169,7 +169,7 @@ class TalkListService
* *
* @param int $user_id 用户ID * @param int $user_id 用户ID
* @param int $receiver_id 接收者ID * @param int $receiver_id 接收者ID
* @param int $talk_type 接收者类型[1:好友;2:群组;] * @param int $talk_type 对话类型[1:私信;2:群聊;]
* @param int $is_disturb 是否免打扰[0:;1:;] * @param int $is_disturb 是否免打扰[0:;1:;]
* @return boolean * @return boolean
*/ */
@ -190,4 +190,21 @@ class TalkListService
'updated_at' => date('Y-m-d H:i:s') 'updated_at' => date('Y-m-d H:i:s')
]); ]);
} }
/**
* 判断是否消息免打扰
*
* @param int $user_id 用户ID
* @param int $receiver_id 接收者ID
* @param int $talk_type 对话类型[1:私信;2:群聊;]
* @return bool
*/
public function isDisturb(int $user_id, int $receiver_id, int $talk_type)
{
return (bool)TalkList::query()->where([
['user_id', '=', $user_id],
['talk_type', '=', $talk_type],
['receiver_id', '=', $receiver_id],
])->value('is_disturb');
}
} }

View File

@ -69,11 +69,12 @@ class UserService extends BaseService
]); ]);
Db::commit(); Db::commit();
return true;
} catch (\Exception $e) { } catch (\Exception $e) {
Db::rollBack(); Db::rollBack();
return false; return false;
} }
return true;
} }
/** /**
@ -118,7 +119,7 @@ class UserService extends BaseService
if (!$info) return []; if (!$info) return [];
$info = $info->toArray(); $info = $info->toArray();
$info['friend_status'] = 0;//朋友关系状态[0:本人;1:陌生人;2:朋友;] $info['friend_status'] = 0;//朋友关系[0:本人;1:陌生人;2:朋友;]
$info['nickname_remark'] = ''; $info['nickname_remark'] = '';
$info['friend_apply'] = 0; $info['friend_apply'] = 0;

View File

@ -48,7 +48,7 @@ return [
], ],
'settings' => [ 'settings' => [
'enable_coroutine' => true, 'enable_coroutine' => true,
'worker_num' => 1, 'worker_num' => env('SWOOLE_CPU_NUM', swoole_cpu_num() * 2),
'pid_file' => BASE_PATH . '/runtime/hyperf.pid', 'pid_file' => BASE_PATH . '/runtime/hyperf.pid',
'open_tcp_nodelay' => true, 'open_tcp_nodelay' => true,
'max_coroutine' => 100000, 'max_coroutine' => 100000,