优化代码及调整接口

main
gzydong 2021-01-28 20:07:14 +08:00
parent fd44a52315
commit 0b860d3fad
7 changed files with 1640 additions and 1488 deletions

View File

@ -0,0 +1,306 @@
<?php
/**
*
* This is my open source code, please do not use it for commercial applications.
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code
*
* @author Yuandong<837215079@qq.com>
* @link https://github.com/gzydong/hyperf-chat
*/
namespace App\Controller\Api\V1;
use App\Model\UsersFriendsApply;
use Co\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\JWTAuthMiddleware;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Amqp\Producer;
use App\Amqp\Producer\ChatMessageProducer;
use App\Service\ContactsService;
use App\Service\SocketClientService;
use App\Service\UserService;
use App\Cache\ApplyNumCache;
use App\Cache\FriendRemarkCache;
use App\Model\UsersChatList;
use App\Constants\SocketConstants;
/**
* Class ContactsController
*
* @Controller(path="/api/v1/contacts")
* @Middleware(JWTAuthMiddleware::class)
*
* @package App\Controller\Api\V1
*/
class ContactsController extends CController
{
/**
* @Inject
* @var ContactsService
*/
private $contactsService;
/**
* @inject
* @var SocketClientService
*/
private $socketClientService;
/**
* @Inject
* @var Producer
*/
private $producer;
/**
* 获取用户联系人列表
*
* @RequestMapping(path="list", methods="get")
*/
public function getContacts()
{
$rows = $this->contactsService->getContacts($this->uid());
if ($rows) {
$runArr = $this->socketClientService->getServerRunIdAll();
foreach ($rows as $k => $row) {
// 查询用户当前是否在线
$rows[$k]['online'] = $this->socketClientService->isOnlineAll($row['id'], $runArr);
}
}
return $this->response->success($rows);
}
/**
* 添加联系人
*
* @RequestMapping(path="add", methods="post")
*
* @param UserService $userService
* @return ResponseInterface
*/
public function addContact(UserService $userService)
{
$params = $this->request->inputs(['friend_id', 'remarks']);
$this->validate($params, [
'friend_id' => 'required|integer',
'remarks' => 'present|max:50'
]);
$user = $userService->findById($params['friend_id']);
if (!$user) {
return $this->response->fail('用户不存在...');
}
$user_id = $this->uid();
if (!$this->contactsService->addContact($user_id, intval($params['friend_id']), $params['remarks'])) {
return $this->response->fail('添加好友申请失败...');
}
// 好友申请未读消息数自增
ApplyNumCache::setInc(intval($params['friend_id']));
//判断对方是否在线。如果在线发送消息通知
if ($this->socketClientService->isOnlineAll(intval($params['friend_id']))) {
$this->producer->produce(
// 消息待完善
new ChatMessageProducer(SocketConstants::EVENT_FRIEND_APPLY, [
'sender' => $user_id,
'receive' => intval($params['friend_id']),
'type' => 1,
'status' => 1,
'remark' => ''
])
);
}
return $this->response->success([], '发送好友申请成功...');
}
/**
* 删除联系人
*
* @RequestMapping(path="delete", methods="post")
*/
public function deleteContact()
{
$params = $this->request->inputs(['friend_id']);
$this->validate($params, [
'friend_id' => 'required|integer'
]);
$user_id = $this->uid();
if (!$this->contactsService->deleteContact($user_id, intval($params['friend_id']))) {
return $this->response->fail('好友关系解除失败...');
}
//删除好友会话列表
UsersChatList::delItem($user_id, $params['friend_id'], 2);
UsersChatList::delItem($params['friend_id'], $user_id, 2);
// ... 推送消息(待完善)
return $this->response->success([], '好友关系解除成功...');
}
/**
* 同意添加联系人
*
* @RequestMapping(path="accept-invitation", methods="post")
*/
public function acceptInvitation()
{
$params = $this->request->inputs(['apply_id', 'remarks']);
$this->validate($params, [
'apply_id' => 'required|integer',
'remarks' => 'present|max:20'
]);
$user_id = $this->uid();
$isTrue = $this->contactsService->acceptInvitation($user_id, intval($params['apply_id']), $params['remarks']);
if (!$isTrue) {
return $this->response->fail('处理失败...');
}
$friend_id = $info = UsersFriendsApply::where('id', $params['apply_id'])
->where('friend_id', $user_id)
->value('user_id');
//判断对方是否在线。如果在线发送消息通知
if ($this->socketClientService->isOnlineAll($friend_id)) {
// 待完善
$this->producer->produce(
new ChatMessageProducer(SocketConstants::EVENT_FRIEND_APPLY, [
'sender' => $user_id,
'receive' => $friend_id,
'type' => 1,
'status' => 1,
'remark' => ''
])
);
}
return $this->response->success([], '处理成功...');
}
/**
* 拒绝添加联系人(预留)
*
* @RequestMapping(path="decline-invitation", methods="post")
*/
public function declineInvitation()
{
$params = $this->request->inputs(['apply_id', 'remarks']);
$this->validate($params, [
'apply_id' => 'required|integer',
'remarks' => 'present|max:20'
]);
$isTrue = $this->contactsService->declineInvitation($this->uid(), intval($params['apply_id']), $params['remarks']);
return $isTrue
? $this->response->success()
: $this->response->fail();
}
/**
* 删除联系人申请记录
*
* @RequestMapping(path="delete-apply", methods="post")
*/
public function deleteContactApply()
{
$params = $this->request->inputs(['apply_id']);
$this->validate($params, [
'apply_id' => 'required|integer'
]);
$isTrue = $this->contactsService->delContactApplyRecord($this->uid(), intval($params['apply_id']));
return $isTrue
? $this->response->success()
: $this->response->fail();
}
/**
* 获取联系人申请未读数
*
* @RequestMapping(path="apply-unread-num", methods="get")
*/
public function getContactApplyUnreadNum()
{
$num = ApplyNumCache::get($this->uid());
return $this->response->success([
'unread_num' => $num ? $num : 0
]);
}
/**
* 获取联系人申请未读数
*
* @RequestMapping(path="apply-records", methods="get")
*/
public function getContactApplyRecords()
{
$params = $this->request->inputs(['page', 'page_size']);
$this->validate($params, [
'page' => 'present|integer',
'page_size' => 'present|integer'
]);
$page = $this->request->input('page', 1);
$page_size = $this->request->input('page_size', 10);
$user_id = $this->uid();
$data = $this->contactsService->getContactApplyRecords($user_id, $page, $page_size);
ApplyNumCache::del($user_id);
return $this->response->success($data);
}
/**
* 搜索联系人
*
* @RequestMapping(path="search", methods="get")
*/
public function searchContacts()
{
$params = $this->request->inputs(['mobile']);
$this->validate($params, [
'mobile' => "present|regex:/^1[3456789][0-9]{9}$/"
]);
$result = $this->contactsService->findContact($params['mobile']);
return $this->response->success($result);
}
/**
* 编辑联系人备注
*
* @RequestMapping(path="edit-remark", methods="post")
*/
public function editContactRemark()
{
$params = $this->request->inputs(['friend_id', 'remarks']);
$this->validate($params, [
'friend_id' => 'required|integer|min:1',
'remarks' => "required|max:20"
]);
$user_id = $this->uid();
$isTrue = $this->contactsService->editContactRemark($user_id, intval($params['friend_id']), $params['remarks']);
if (!$isTrue) {
return $this->response->fail('备注修改失败...');
}
FriendRemarkCache::set($user_id, intval($params['friend_id']), $params['remarks']);
return $this->response->success([], '备注修改成功...');
}
}

View File

@ -9,6 +9,7 @@
* @author Yuandong<837215079@qq.com> * @author Yuandong<837215079@qq.com>
* @link https://github.com/gzydong/hyperf-chat * @link https://github.com/gzydong/hyperf-chat
*/ */
namespace App\Controller\Api\V1; namespace App\Controller\Api\V1;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
@ -314,7 +315,7 @@ class GroupController extends CController
} }
/** /**
* 设置用户群名片 * 设置群名片
* *
* @RequestMapping(path="set-group-card", methods="post") * @RequestMapping(path="set-group-card", methods="post")
*/ */
@ -337,7 +338,7 @@ class GroupController extends CController
} }
/** /**
* 获取用户可邀请加入群组的好友列表 * 获取可邀请加入群组的好友列表
* *
* @RequestMapping(path="invite-friends", methods="get") * @RequestMapping(path="invite-friends", methods="get")
*/ */
@ -358,6 +359,18 @@ class GroupController extends CController
return $this->response->success($friends); return $this->response->success($friends);
} }
/**
* 获取群组列表
*
* @RequestMapping(path="list", methods="get")
*/
public function getGroups()
{
return $this->response->success(
$this->groupService->getGroups($this->uid())
);
}
/** /**
* 获取群组成员列表 * 获取群组成员列表
* *

View File

@ -16,20 +16,11 @@ 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 Hyperf\Amqp\Producer;
use App\Amqp\Producer\ChatMessageProducer;
use App\Model\User; use App\Model\User;
use App\Model\UsersChatList;
use App\Model\UsersFriend;
use App\Support\SendEmailCode; use App\Support\SendEmailCode;
use App\Helper\Hash; use App\Helper\Hash;
use App\Service\FriendService;
use App\Service\UserService; use App\Service\UserService;
use App\Service\SocketClientService;
use App\Service\SmsCodeService; use App\Service\SmsCodeService;
use App\Cache\ApplyNumCache;
use App\Cache\FriendRemarkCache;
use App\Constants\SocketConstants;
use App\Constants\ResponseCode; use App\Constants\ResponseCode;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -43,83 +34,12 @@ use Psr\Http\Message\ResponseInterface;
*/ */
class UsersController extends CController class UsersController extends CController
{ {
/**
* @Inject
* @var FriendService
*/
private $friendService;
/** /**
* @Inject * @Inject
* @var UserService * @var UserService
*/ */
private $userService; private $userService;
/**
* @inject
* @var SocketClientService
*/
private $socketClientService;
/**
* @Inject
* @var Producer
*/
private $producer;
/**
* 获取我的好友列表
*
* @RequestMapping(path="friends", methods="get")
*/
public function getUserFriends()
{
$rows = UsersFriend::getUserFriends($this->uid());
$runArr = $this->socketClientService->getServerRunIdAll();
foreach ($rows as $k => $row) {
$rows[$k]['online'] = $this->socketClientService->isOnlineAll($row['id'], $runArr);
}
return $this->response->success($rows);
}
/**
* 解除好友关系
*
* @RequestMapping(path="remove-friend", methods="post")
*/
public function removeFriend()
{
$params = $this->request->inputs(['friend_id']);
$this->validate($params, [
'friend_id' => 'required|integer'
]);
$user_id = $this->uid();
if (!$this->friendService->removeFriend($user_id, $params['friend_id'])) {
return $this->response->fail('好友关系解除成功...');
}
//删除好友会话列表
UsersChatList::delItem($user_id, $params['friend_id'], 2);
UsersChatList::delItem($params['friend_id'], $user_id, 2);
return $this->response->success([], '好友关系解除成功...');
}
/**
* 获取用户群聊列表
*
* @RequestMapping(path="user-groups", methods="get")
*/
public function getUserGroups()
{
return $this->response->success(
$this->userService->getUserChatGroups($this->uid())
);
}
/** /**
* 获取我的信息 * 获取我的信息
* *
@ -212,182 +132,16 @@ class UsersController extends CController
*/ */
public function searchUserInfo() public function searchUserInfo()
{ {
$params = $this->request->inputs(['user_id', 'mobile']); $params = $this->request->inputs(['user_id']);
$this->validate($params, ['user_id' => 'required|integer']);
if (isset($params['user_id']) && !empty($params['user_id'])) { if ($data = $this->userService->getUserCard($params['user_id'],$this->uid())) {
$this->validate($params, ['user_id' => 'present|integer']);
$where['uid'] = $params['user_id'];
} else if (isset($params['mobile']) && !empty($params['mobile'])) {
$this->validate($params, ['mobile' => "present|regex:/^1[345789][0-9]{9}$/"]);
$where['mobile'] = $params['mobile'];
} else {
return $this->response->fail('请求参数不正确...', [], ResponseCode::VALIDATION_ERROR);
}
if ($data = $this->userService->searchUserInfo($where, $this->uid())) {
return $this->response->success($data); return $this->response->success($data);
} }
return $this->response->fail('查询失败...'); return $this->response->fail('查询失败...');
} }
/**
* 编辑好友备注信息
*
* @RequestMapping(path="edit-friend-remark", methods="post")
*/
public function editFriendRemark()
{
$params = $this->request->inputs(['friend_id', 'remarks']);
$this->validate($params, [
'friend_id' => 'required|integer|min:1',
'remarks' => "required|max:20"
]);
$user_id = $this->uid();
$isTrue = $this->friendService->editFriendRemark($user_id, $params['friend_id'], $params['remarks']);
if ($isTrue) {
FriendRemarkCache::set($user_id, (int)$params['friend_id'], $params['remarks']);
}
return $isTrue
? $this->response->success([], '备注修改成功...')
: $this->response->fail('备注修改失败...');
}
/**
* 发送添加好友申请
*
* @RequestMapping(path="send-friend-apply", methods="post")
*/
public function sendFriendApply()
{
$params = $this->request->inputs(['friend_id', 'remarks']);
$this->validate($params, [
'friend_id' => 'required|integer',
'remarks' => 'present|max:50'
]);
$user = $this->userService->findById($params['friend_id']);
if (!$user) {
return $this->response->fail('用户不存在...');
}
$user_id = $this->uid();
if (!$this->friendService->addFriendApply($user_id, (int)$params['friend_id'], $params['remarks'])) {
return $this->response->fail('发送好友申请失败...');
}
// 好友申请未读消息数自增
ApplyNumCache::setInc((int)$params['friend_id']);
//判断对方是否在线。如果在线发送消息通知
if ($this->socketClientService->isOnlineAll((int)$params['friend_id'])) {
$this->producer->produce(
new ChatMessageProducer(SocketConstants::EVENT_FRIEND_APPLY, [
'sender' => $user_id,
'receive' => (int)$params['friend_id'],
'type' => 1,
'status' => 1,
'remark' => ''
])
);
}
return $this->response->success([], '发送好友申请成功...');
}
/**
* 处理好友的申请
*
* @RequestMapping(path="handle-friend-apply", methods="post")
*/
public function handleFriendApply()
{
$params = $this->request->inputs(['apply_id', 'remarks']);
$this->validate($params, [
'apply_id' => 'required|integer',
'remarks' => 'present|max:20'
]);
$user_id = $this->uid();
$isTrue = $this->friendService->handleFriendApply($this->uid(), (int)$params['apply_id'], $params['remarks']);
if (!$isTrue) {
return $this->response->fail('处理失败...');
}
//判断对方是否在线。如果在线发送消息通知
if ($this->socketClientService->isOnlineAll((int)$params['friend_id'])) {
// 待修改
$this->producer->produce(
new ChatMessageProducer(SocketConstants::EVENT_FRIEND_APPLY, [
'sender' => $user_id,
'receive' => (int)$params['friend_id'],
'type' => 1,
'status' => 1,
'remark' => ''
])
);
}
return $this->response->success([], '处理成功...');
}
/**
* 删除好友申请记录
*
* @RequestMapping(path="delete-friend-apply", methods="post")
*/
public function deleteFriendApply()
{
$params = $this->request->inputs(['apply_id']);
$this->validate($params, [
'apply_id' => 'required|integer'
]);
$isTrue = $this->friendService->delFriendApply($this->uid(), (int)$params['apply_id']);
return $isTrue
? $this->response->success([], '删除成功...')
: $this->response->fail('删除失败...');
}
/**
* 获取我的好友申请记录
*
* @RequestMapping(path="friend-apply-records", methods="get")
*/
public function getFriendApplyRecords()
{
$params = $this->request->inputs(['page', 'page_size']);
$this->validate($params, [
'page' => 'present|integer',
'page_size' => 'present|integer'
]);
$page = $this->request->input('page', 1);
$page_size = $this->request->input('page_size', 10);
$user_id = $this->uid();
$data = $this->friendService->findApplyRecords($user_id, $page, $page_size);
ApplyNumCache::del($user_id);
return $this->response->success($data);
}
/**
* 获取好友申请未读数
*
* @RequestMapping(path="friend-apply-num", methods="get")
*/
public function getApplyUnreadNum()
{
$num = ApplyNumCache::get($this->uid());
return $this->response->success([
'unread_num' => $num ? $num : 0
]);
}
/** /**
* 修改我的密码 * 修改我的密码
* *

View File

@ -0,0 +1,287 @@
<?php
/**
*
* This is my open source code, please do not use it for commercial applications.
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code
*
* @author Yuandong<837215079@qq.com>
* @link https://github.com/gzydong/hyperf-chat
*/
namespace App\Service;
use App\Model\User;
use App\Model\UsersFriend;
use App\Model\UsersFriendsApply;
use App\Traits\PagingTrait;
use Hyperf\DbConnection\Db;
use Exception;
/**
* ContactsService
* 注:联系人服务层
*
* @package App\Service
*/
class ContactsService extends BaseService
{
use PagingTrait;
/**
* 获取联系人列表
*
* @param int $user_id 用户ID
* @return array
*/
public function getContacts(int $user_id): array
{
$prefix = config('databases.default.prefix');
$sql = <<<SQL
SELECT users.id,users.nickname,users.avatar,users.motto,users.gender,tmp_table.friend_remark from {$prefix}users users
INNER join
(
SELECT id as rid,user2 as uid,user1_remark as friend_remark from {$prefix}users_friends where user1 = {$user_id} and `status` = 1
UNION all
SELECT id as rid,user1 as uid,user2_remark as friend_remark from {$prefix}users_friends where user2 = {$user_id} and `status` = 1
) tmp_table on tmp_table.uid = users.id
SQL;
$rows = Db::select($sql);
array_walk($rows, function (&$item) {
$item = (array)$item;
});
return $rows;
}
/**
* 添加联系人/申请
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @param string $remarks 申请备注
* @return bool
*/
public function addContact(int $user_id, int $friend_id, string $remarks): bool
{
// 判断是否是好友关系
if (UsersFriend::isFriend($user_id, $friend_id)) return true;
// 查询最后一次联系人申请
$result = UsersFriendsApply::where('user_id', $user_id)
->where('friend_id', $friend_id)
->orderBy('id', 'desc')->first();
if (!$result) {
$result = UsersFriendsApply::create([
'user_id' => $user_id,
'friend_id' => $friend_id,
'status' => 0,
'remarks' => $remarks,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
return $result ? true : false;
} else if ($result->status == 0) {
$result->remarks = $remarks;
$result->updated_at = date('Y-m-d H:i:s');
$result->save();
return true;
}
return false;
}
/**
* 删除联系人
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @return bool
*/
public function deleteContact(int $user_id, int $friend_id): bool
{
if (!UsersFriend::isFriend($user_id, $friend_id)) {
return false;
}
$data = ['status' => 0];
// 用户ID比大小交换位置
if ($user_id > $friend_id) {
[$user_id, $friend_id] = [$friend_id, $user_id];
}
return (bool)UsersFriend::where('user1', $user_id)->where('user2', $friend_id)->update($data);
}
/**
* 同意添加联系人 / 联系人申请
*
* @param int $user_id 用户ID
* @param int $apply_id 联系人申请ID
* @param string $remarks 联系人备注名称
* @return bool
*/
public function acceptInvitation(int $user_id, int $apply_id, string $remarks = ''): bool
{
$info = UsersFriendsApply::where('id', $apply_id)
->where('friend_id', $user_id)
->where('status', 0)
->orderBy('id', 'desc')
->first(['user_id', 'friend_id']);
if (!$info) return false;
Db::beginTransaction();
try {
$res = UsersFriendsApply::where('id', $apply_id)->update(['status' => 1, 'updated_at' => date('Y-m-d H:i:s')]);
if (!$res) {
throw new Exception('更新好友申请表信息失败');
}
// 判断大小 交换 user1,user2 的位置
[$user1, $user2] = $info->user_id < $info->friend_id ? [$info->user_id, $info->friend_id] : [$info->friend_id, $info->user_id];
// 查询是否存在好友记录
$friendResult = UsersFriend::where([
['user1', '=', $user1],
['user2', '=', $user2]
])->first(['id', 'user1', 'user2', 'active', 'status']);
if ($friendResult) {
$active = ($friendResult->user1 == $info->user_id && $friendResult->user2 == $info->friend_id) ? 1 : 2;
UsersFriend::where('id', $friendResult->id)->update(['active' => $active, 'status' => 1]);
} else {
//好友昵称
$friend_nickname = User::where('id', $info->friend_id)->value('nickname');
UsersFriend::create([
'user1' => $user1,
'user2' => $user2,
'user1_remark' => $user1 == $user_id ? $remarks : $friend_nickname,
'user2_remark' => $user2 == $user_id ? $remarks : $friend_nickname,
'active' => $user1 == $user_id ? 2 : 1,
'status' => 1,
'agree_time' => date('Y-m-d H:i:s'),
'created_at' => date('Y-m-d H:i:s')
]);
}
Db::commit();
} catch (Exception $e) {
Db::rollBack();
return false;
}
return true;
}
/**
* 拒绝添加联系人 / 联系人申请
*
* @param int $user_id 用户ID
* @param int $apply_id 联系人申请ID
* @param string $remarks 拒绝申请备注信息
* @return bool
*/
public function declineInvitation(int $user_id, int $apply_id, string $remarks = ''): bool
{
$result = UsersFriendsApply::where([
['id', '=', $apply_id],
['user_id', '=', $user_id],
['status', '=', 2],
])->update([
'status' => 2,
'remarks' => $remarks,
'updated_at' => date('Y-m-d H:i:s')
]);
return $result ? true : false;
}
/**
* 编辑联系人备注
*
* @param int $user_id 用户ID
* @param int $friend_id 朋友ID
* @param string $remarks 好友备注名称
* @return bool
*/
public function editContactRemark(int $user_id, int $friend_id, string $remarks): bool
{
$data = [];
if ($user_id > $friend_id) {
[$user_id, $friend_id] = [$friend_id, $user_id];
$data['user2_remark'] = $remarks;
} else {
$data['user1_remark'] = $remarks;
}
return (bool)UsersFriend::where('user1', $user_id)->where('user2', $friend_id)->update($data);
}
/**
* 搜索联系人
*
* @param string $mobile 用户手机号/登录账号
* @return array
*/
public function findContact(string $mobile): array
{
$user = User::where('mobile', $mobile)->first(['id', 'nickname', 'mobile', 'avatar', 'gender']);
return $user ? $user->toArray() : [];
}
/**
* 获取联系人申请记录
*
* @param int $user_id 用户ID
* @param int $page 当前分页
* @param int $page_size 分页大小
* @return array
*/
public function getContactApplyRecords(int $user_id, $page = 1, $page_size = 30): array
{
$rowsSqlObj = UsersFriendsApply::select([
'users_friends_apply.id',
'users_friends_apply.status',
'users_friends_apply.remarks',
'users.nickname',
'users.avatar',
'users.mobile',
'users_friends_apply.user_id',
'users_friends_apply.friend_id',
'users_friends_apply.created_at'
]);
$rowsSqlObj->leftJoin('users', 'users.id', '=', 'users_friends_apply.user_id');
$rowsSqlObj->where('users_friends_apply.friend_id', $user_id);
$count = $rowsSqlObj->count();
$rows = [];
if ($count > 0) {
$rows = $rowsSqlObj->orderBy('users_friends_apply.id', 'desc')->forPage($page, $page_size)->get()->toArray();
}
return $this->getPagingRows($rows, $count, $page, $page_size);
}
/**
* 删除联系人申请记录
*
* @param int $user_id 用户ID
* @param int $apply_id 联系人好友申请ID
* @return bool
*/
public function delContactApplyRecord(int $user_id, int $apply_id): bool
{
return (bool)UsersFriendsApply::where('id', $apply_id)->where('friend_id', $user_id)->delete();
}
}

View File

@ -1,205 +0,0 @@
<?php
namespace App\Service;
use App\Model\User;
use App\Model\UsersFriend;
use App\Model\UsersFriendsApply;
use App\Traits\PagingTrait;
use Hyperf\DbConnection\Db;
class FriendService extends BaseService
{
use PagingTrait;
/**
* 创建好友的申请
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @param string $remarks 好友申请备注
* @return bool
*/
public function addFriendApply(int $user_id, int $friend_id, string $remarks)
{
// 判断是否是好友关系
if (UsersFriend::isFriend($user_id, $friend_id)) {
return true;
}
$result = UsersFriendsApply::where('user_id', $user_id)->where('friend_id', $friend_id)->orderBy('id', 'desc')->first();
if (!$result) {
$result = UsersFriendsApply::create([
'user_id' => $user_id,
'friend_id' => $friend_id,
'status' => 0,
'remarks' => $remarks,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
return $result ? true : false;
} else if ($result->status == 0) {
$result->remarks = $remarks;
$result->updated_at = date('Y-m-d H:i:s');
$result->save();
return true;
}
return false;
}
/**
* 删除好友申请记录
*
* @param int $user_id 用户ID
* @param int $apply_id 好友申请ID
* @return mixed
*/
public function delFriendApply(int $user_id, int $apply_id)
{
return (bool)UsersFriendsApply::where('id', $apply_id)->where('friend_id', $user_id)->delete();
}
/**
* 处理好友的申请
*
* @param int $user_id 当前用户ID
* @param int $apply_id 申请记录ID
* @param string $remarks 备注信息
* @return bool
*/
public function handleFriendApply(int $user_id, int $apply_id, $remarks = '')
{
$info = UsersFriendsApply::where('id', $apply_id)->where('friend_id', $user_id)->where('status', 0)->orderBy('id', 'desc')->first(['user_id', 'friend_id']);
if (!$info) {
return false;
}
Db::beginTransaction();
try {
$res = UsersFriendsApply::where('id', $apply_id)->update(['status' => 1, 'updated_at' => date('Y-m-d H:i:s')]);
if (!$res) {
throw new \Exception('更新好友申请表信息失败');
}
$user1 = $info->user_id;
$user2 = $info->friend_id;
if ($info->user_id > $info->friend_id) {
[$user1, $user2] = [$info->friend_id, $info->user_id];
}
//查询是否存在好友记录
$friendResult = UsersFriend::select('id', 'user1', 'user2', 'active', 'status')->where('user1', '=', $user1)->where('user2', '=', $user2)->first();
if ($friendResult) {
$active = ($friendResult->user1 == $info->user_id && $friendResult->user2 == $info->friend_id) ? 1 : 2;
if (!UsersFriend::where('id', $friendResult->id)->update(['active' => $active, 'status' => 1])) {
throw new \Exception('更新好友关系信息失败');
}
} else {
//好友昵称
$friend_nickname = User::where('id', $info->friend_id)->value('nickname');
$insRes = UsersFriend::create([
'user1' => $user1,
'user2' => $user2,
'user1_remark' => $user1 == $user_id ? $remarks : $friend_nickname,
'user2_remark' => $user2 == $user_id ? $remarks : $friend_nickname,
'active' => $user1 == $user_id ? 2 : 1,
'status' => 1,
'agree_time' => date('Y-m-d H:i:s'),
'created_at' => date('Y-m-d H:i:s')
]);
if (!$insRes) {
throw new \Exception('创建好友关系失败');
}
}
Db::commit();
} catch (\Exception $e) {
Db::rollBack();
return false;
}
return true;
}
/**
* 解除好友关系
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @return bool
*/
public function removeFriend(int $user_id, int $friend_id)
{
if (!UsersFriend::isFriend($user_id, $friend_id)) {
return false;
}
$data = ['status' => 0];
// 用户ID比大小交换位置
if ($user_id > $friend_id) {
[$user_id, $friend_id] = [$friend_id, $user_id];
}
return (bool)UsersFriend::where('user1', $user_id)->where('user2', $friend_id)->update($data);
}
/**
* 获取用户好友申请记录
*
* @param int $user_id 用户ID
* @param int $page 分页数
* @param int $page_size 分页大小
* @return array
*/
public function findApplyRecords(int $user_id, $page = 1, $page_size = 30)
{
$rowsSqlObj = UsersFriendsApply::select([
'users_friends_apply.id',
'users_friends_apply.status',
'users_friends_apply.remarks',
'users.nickname',
'users.avatar',
'users.mobile',
'users_friends_apply.user_id',
'users_friends_apply.friend_id',
'users_friends_apply.created_at'
]);
$rowsSqlObj->leftJoin('users', 'users.id', '=', 'users_friends_apply.user_id');
$rowsSqlObj->where('users_friends_apply.friend_id', $user_id);
$count = $rowsSqlObj->count();
$rows = [];
if ($count > 0) {
$rows = $rowsSqlObj->orderBy('users_friends_apply.id', 'desc')->forPage($page, $page_size)->get()->toArray();
}
return $this->getPagingRows($rows, $count, $page, $page_size);
}
/**
* 编辑好友备注信息
*
* @param int $user_id 用户ID
* @param int $friend_id 朋友ID
* @param string $remarks 好友备注名称
* @return bool
*/
public function editFriendRemark(int $user_id, int $friend_id, string $remarks)
{
$data = [];
if ($user_id > $friend_id) {
[$user_id, $friend_id] = [$friend_id, $user_id];
$data['user2_remark'] = $remarks;
} else {
$data['user1_remark'] = $remarks;
}
return (bool)UsersFriend::where('user1', $user_id)->where('user2', $friend_id)->update($data);
}
}

View File

@ -17,6 +17,45 @@ use Exception;
*/ */
class GroupService extends BaseService class GroupService extends BaseService
{ {
/**
* 获取用户所在的群聊
*
* @param int $user_id 用户ID
* @return array
*/
public function getGroups(int $user_id): array
{
$fields = [
'users_group.id', 'users_group.group_name', 'users_group.avatar',
'users_group.group_profile', 'users_group.user_id as group_user_id'
];
$items = UsersGroupMember::join('users_group', 'users_group.id', '=', 'users_group_member.group_id')
->where([
['users_group_member.user_id', '=', $user_id],
['users_group_member.status', '=', 0]
])
->orderBy('id', 'desc')
->get($fields)->toArray();
foreach ($items as $key => $item) {
// 判断当前用户是否是群主
$items[$key]['isGroupLeader'] = $item['group_user_id'] == $user_id;
//删除无关字段
unset($items[$key]['group_user_id']);
// 是否消息免打扰
$items[$key]['not_disturb'] = UsersChatList::where([
['uid', '=', $user_id],
['type', '=', 2],
['group_id', '=', $item['id']]
])->value('not_disturb');
}
return $items;
}
/** /**
* 创建群组 * 创建群组
* *

View File

@ -3,10 +3,8 @@
namespace App\Service; namespace App\Service;
use App\Helper\Hash; use App\Helper\Hash;
use App\Model\Group\UsersGroupMember;
use App\Model\User; use App\Model\User;
use App\Model\Article\ArticleClass; use App\Model\Article\ArticleClass;
use App\Model\UsersChatList;
use App\Model\UsersFriend; use App\Model\UsersFriend;
use App\Model\UsersFriendsApply; use App\Model\UsersFriendsApply;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
@ -107,84 +105,44 @@ class UserService extends BaseService
return [$isTrue, null]; return [$isTrue, null];
} }
/**
* 获取用户所在的群聊
*
* @param int $user_id 用户ID
* @return mixed
*/
public function getUserChatGroups(int $user_id)
{
$items = UsersGroupMember::select(['users_group.id', 'users_group.group_name', 'users_group.avatar', 'users_group.group_profile', 'users_group.user_id as group_user_id'])
->join('users_group', 'users_group.id', '=', 'users_group_member.group_id')
->where([
['users_group_member.user_id', '=', $user_id],
['users_group_member.status', '=', 0]
])
->orderBy('id', 'desc')->get()->toarray();
foreach ($items as $key => $item) {
// 判断当前用户是否是群主
$items[$key]['isGroupLeader'] = $item['group_user_id'] == $user_id;
//删除无关字段
unset($items[$key]['group_user_id']);
// 是否消息免打扰
$items[$key]['not_disturb'] = UsersChatList::where([
['uid', '=', $user_id],
['type', '=', 2],
['group_id', '=', $item['id']]
])->value('not_disturb');
}
return $items;
}
/** /**
* 通过手机号查找用户 * 通过手机号查找用户
* *
* @param array $where 查询条件 * @param int $friend_id 用户ID
* @param int $user_id 当前登录用户的ID * @param int $me_user_id 当前登录用户的ID
* @return array * @return array
*/ */
public function searchUserInfo(array $where, int $user_id) public function getUserCard(int $friend_id,int $me_user_id)
{ {
$info = User::select(['id', 'mobile', 'nickname', 'avatar', 'gender', 'motto']); $info = User::select(['id', 'mobile', 'nickname', 'avatar', 'gender', 'motto'])->where('id', $friend_id)->first();
if (isset($where['uid'])) { if(!$info) return [];
$info->where('id', $where['uid']);
}
if (isset($where['mobile'])) { $info = $info->toArray();
$info->where('mobile', $where['mobile']);
}
$info = $info->first();
$info = $info ? $info->toArray() : [];
if ($info) {
$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;
// 判断查询信息是否是自己 // 判断查询信息是否是自己
if ($info['id'] != $user_id) { if ($friend_id != $me_user_id) {
$friend_id = $info['id']; $friendInfo = UsersFriend::
where('user1', '=', $friend_id > $me_user_id ? $me_user_id :$friend_id)
$friendInfo = UsersFriend::select('id', 'user1', 'user2', 'active', 'user1_remark', 'user2_remark')->where(function ($query) use ($friend_id, $user_id) { ->where('user2', '=', $friend_id < $me_user_id ? $me_user_id :$friend_id)
$query->where('user1', '=', $user_id)->where('user2', '=', $friend_id)->where('status', 1); ->where('status', 1)
})->orWhere(function ($query) use ($friend_id, $user_id) { ->first(['id', 'user1', 'user2', 'active', 'user1_remark', 'user2_remark']);
$query->where('user1', '=', $friend_id)->where('user2', '=', $user_id)->where('status', 1);
})->first();
$info['friend_status'] = $friendInfo ? 2 : 1; $info['friend_status'] = $friendInfo ? 2 : 1;
if ($friendInfo) { if ($friendInfo) {
$info['nickname_remark'] = ($friendInfo->user1 == $friend_id) ? $friendInfo->user2_remark : $friendInfo->user1_remark; $info['nickname_remark'] = $friendInfo->user1 == $friend_id ? $friendInfo->user2_remark : $friendInfo->user1_remark;
} else { } else {
$res = UsersFriendsApply::where('user_id', $user_id)->where('friend_id', $info['id'])->where('status', 0)->orderBy('id', 'desc')->exists(); $res = UsersFriendsApply::where('user_id', $me_user_id)
->where('friend_id', $friend_id)
->where('status', 0)
->orderBy('id', 'desc')
->exists();
$info['friend_apply'] = $res ? 1 : 0; $info['friend_apply'] = $res ? 1 : 0;
} }
} }
}
return $info; return $info;
} }