优化代码及调整接口

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([], '备注修改成功...');
}
}

File diff suppressed because it is too large Load Diff

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

@ -1,336 +1,375 @@
<?php <?php
namespace App\Service; namespace App\Service;
use App\Cache\LastMsgCache; use App\Cache\LastMsgCache;
use App\Model\Chat\ChatRecord; use App\Model\Chat\ChatRecord;
use App\Model\Chat\ChatRecordsInvite; use App\Model\Chat\ChatRecordsInvite;
use App\Model\Group\UsersGroup; use App\Model\Group\UsersGroup;
use App\Model\Group\UsersGroupMember; use App\Model\Group\UsersGroupMember;
use App\Model\UsersChatList; use App\Model\UsersChatList;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
use Exception; use Exception;
/** /**
* Class GroupService * Class GroupService
* @package App\Service * @package App\Service
*/ */
class GroupService extends BaseService class GroupService extends BaseService
{ {
/** /**
* 创建群组 * 获取用户所在的群聊
* *
* @param int $user_id 用户ID * @param int $user_id 用户ID
* @param array $group_info 群聊名称 * @return array
* @param array $friend_ids 好友的用户ID */
* @return array public function getGroups(int $user_id): array
*/ {
public function create(int $user_id, array $group_info, $friend_ids = []) $fields = [
{ 'users_group.id', 'users_group.group_name', 'users_group.avatar',
$friend_ids[] = $user_id; 'users_group.group_profile', 'users_group.user_id as group_user_id'
$groupMember = []; ];
$chatList = [];
$items = UsersGroupMember::join('users_group', 'users_group.id', '=', 'users_group_member.group_id')
Db::beginTransaction(); ->where([
try { ['users_group_member.user_id', '=', $user_id],
$insRes = UsersGroup::create([ ['users_group_member.status', '=', 0]
'user_id' => $user_id, ])
'group_name' => $group_info['name'], ->orderBy('id', 'desc')
'avatar' => $group_info['avatar'], ->get($fields)->toArray();
'group_profile' => $group_info['profile'],
'status' => 0, foreach ($items as $key => $item) {
'created_at' => date('Y-m-d H:i:s') // 判断当前用户是否是群主
]); $items[$key]['isGroupLeader'] = $item['group_user_id'] == $user_id;
if (!$insRes) { //删除无关字段
throw new Exception('创建群失败'); unset($items[$key]['group_user_id']);
}
// 是否消息免打扰
foreach ($friend_ids as $k => $uid) { $items[$key]['not_disturb'] = UsersChatList::where([
$groupMember[] = [ ['uid', '=', $user_id],
'group_id' => $insRes->id, ['type', '=', 2],
'user_id' => $uid, ['group_id', '=', $item['id']]
'group_owner' => $user_id == $uid ? 1 : 0, ])->value('not_disturb');
'status' => 0, }
'created_at' => date('Y-m-d H:i:s'),
]; return $items;
}
$chatList[] = [
'type' => 2, /**
'uid' => $uid, * 创建群组
'friend_id' => 0, *
'group_id' => $insRes->id, * @param int $user_id 用户ID
'status' => 1, * @param array $group_info 群聊名称
'created_at' => date('Y-m-d H:i:s'), * @param array $friend_ids 好友的用户ID
'updated_at' => date('Y-m-d H:i:s') * @return array
]; */
} public function create(int $user_id, array $group_info, $friend_ids = [])
{
if (!Db::table('users_group_member')->insert($groupMember)) { $friend_ids[] = $user_id;
throw new Exception('创建群成员信息失败'); $groupMember = [];
} $chatList = [];
if (!Db::table('users_chat_list')->insert($chatList)) { Db::beginTransaction();
throw new Exception('创建群成员的聊天列表失败'); try {
} $insRes = UsersGroup::create([
'user_id' => $user_id,
$result = ChatRecord::create([ 'group_name' => $group_info['name'],
'msg_type' => 3, 'avatar' => $group_info['avatar'],
'source' => 2, 'group_profile' => $group_info['profile'],
'user_id' => 0, 'status' => 0,
'receive_id' => $insRes->id, 'created_at' => date('Y-m-d H:i:s')
'created_at' => date('Y-m-d H:i:s') ]);
]);
if (!$insRes) {
if (!$result) { throw new Exception('创建群失败');
throw new Exception('创建群成员的聊天列表失败'); }
}
foreach ($friend_ids as $k => $uid) {
ChatRecordsInvite::create([ $groupMember[] = [
'record_id' => $result->id, 'group_id' => $insRes->id,
'type' => 1, 'user_id' => $uid,
'operate_user_id' => $user_id, 'group_owner' => $user_id == $uid ? 1 : 0,
'user_ids' => implode(',', $friend_ids) 'status' => 0,
]); 'created_at' => date('Y-m-d H:i:s'),
];
Db::commit();
} catch (Exception $e) { $chatList[] = [
Db::rollBack(); 'type' => 2,
logger()->error($e); 'uid' => $uid,
return [false, 0]; 'friend_id' => 0,
} 'group_id' => $insRes->id,
'status' => 1,
// 设置群聊消息缓存 'created_at' => date('Y-m-d H:i:s'),
LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $insRes->id, 0); 'updated_at' => date('Y-m-d H:i:s')
];
return [true, ['record_id' => $result->id, 'group_id' => $insRes->id]]; }
}
if (!Db::table('users_group_member')->insert($groupMember)) {
/** throw new Exception('创建群成员信息失败');
* 解散群组 }
*
* @param int $group_id 群ID if (!Db::table('users_chat_list')->insert($chatList)) {
* @param int $user_id 用户ID throw new Exception('创建群成员的聊天列表失败');
* @return bool }
*/
public function dismiss(int $group_id, int $user_id) $result = ChatRecord::create([
{ 'msg_type' => 3,
if (!UsersGroup::where('id', $group_id)->where('status', 0)->exists()) { 'source' => 2,
return false; 'user_id' => 0,
} 'receive_id' => $insRes->id,
'created_at' => date('Y-m-d H:i:s')
//判断执行者是否属于群主 ]);
if (!UsersGroup::isManager($user_id, $group_id)) {
return false; if (!$result) {
} throw new Exception('创建群成员的聊天列表失败');
}
Db::beginTransaction();
try { ChatRecordsInvite::create([
UsersGroup::where('id', $group_id)->update(['status' => 1]); 'record_id' => $result->id,
UsersGroupMember::where('group_id', $group_id)->update(['status' => 1]); 'type' => 1,
Db::commit(); 'operate_user_id' => $user_id,
} catch (Exception $e) { 'user_ids' => implode(',', $friend_ids)
Db::rollBack(); ]);
return false;
} Db::commit();
} catch (Exception $e) {
return true; Db::rollBack();
} logger()->error($e);
return [false, 0];
/** }
* 邀请加入群组
* // 设置群聊消息缓存
* @param int $user_id 用户ID LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $insRes->id, 0);
* @param int $group_id 聊天群ID
* @param array $friend_ids 被邀请的用户ID return [true, ['record_id' => $result->id, 'group_id' => $insRes->id]];
* @return array }
*/
public function invite(int $user_id, int $group_id, $friend_ids = []) /**
{ * 解散群组
$info = UsersGroupMember::select(['id', 'status'])->where('group_id', $group_id)->where('user_id', $user_id)->first(); *
* @param int $group_id 群ID
//判断主动邀请方是否属于聊天群成员 * @param int $user_id 用户ID
if (!$info && $info->status == 1) { * @return bool
return [false, 0]; */
} public function dismiss(int $group_id, int $user_id)
{
if (empty($friend_ids)) { if (!UsersGroup::where('id', $group_id)->where('status', 0)->exists()) {
return [false, 0]; return false;
} }
$updateArr = $insertArr = $updateArr1 = $insertArr1 = []; //判断执行者是否属于群主
if (!UsersGroup::isManager($user_id, $group_id)) {
$members = UsersGroupMember::where('group_id', $group_id)->whereIn('user_id', $friend_ids)->get(['id', 'user_id', 'status'])->keyBy('user_id')->toArray(); return false;
$chatArr = UsersChatList::where('group_id', $group_id)->whereIn('uid', $friend_ids)->get(['id', 'uid', 'status'])->keyBy('uid')->toArray(); }
foreach ($friend_ids as $uid) { Db::beginTransaction();
if (!isset($members[$uid])) {//存在聊天群成员记录 try {
$insertArr[] = ['group_id' => $group_id, 'user_id' => $uid, 'group_owner' => 0, 'status' => 0, 'created_at' => date('Y-m-d H:i:s')]; UsersGroup::where('id', $group_id)->update(['status' => 1]);
} else if ($members[$uid]['status'] == 1) { UsersGroupMember::where('group_id', $group_id)->update(['status' => 1]);
$updateArr[] = $members[$uid]['id']; Db::commit();
} } catch (Exception $e) {
Db::rollBack();
if (!isset($chatArr[$uid])) { return false;
$insertArr1[] = ['type' => 2, 'uid' => $uid, 'friend_id' => 0, 'group_id' => $group_id, 'status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]; }
} else if ($chatArr[$uid]['status'] == 0) {
$updateArr1[] = $chatArr[$uid]['id']; return true;
} }
}
/**
try { * 邀请加入群组
if ($updateArr) { *
UsersGroupMember::whereIn('id', $updateArr)->update(['status' => 0]); * @param int $user_id 用户ID
} * @param int $group_id 聊天群ID
* @param array $friend_ids 被邀请的用户ID
if ($insertArr) { * @return array
Db::table('users_group_member')->insert($insertArr); */
} public function invite(int $user_id, int $group_id, $friend_ids = [])
{
if ($updateArr1) { $info = UsersGroupMember::select(['id', 'status'])->where('group_id', $group_id)->where('user_id', $user_id)->first();
UsersChatList::whereIn('id', $updateArr1)->update(['status' => 1, 'created_at' => date('Y-m-d H:i:s')]);
} //判断主动邀请方是否属于聊天群成员
if (!$info && $info->status == 1) {
if ($insertArr1) { return [false, 0];
Db::table('users_chat_list')->insert($insertArr1); }
}
if (empty($friend_ids)) {
$result = ChatRecord::create([ return [false, 0];
'msg_type' => 3, }
'source' => 2,
'user_id' => 0, $updateArr = $insertArr = $updateArr1 = $insertArr1 = [];
'receive_id' => $group_id,
'created_at' => date('Y-m-d H:i:s') $members = UsersGroupMember::where('group_id', $group_id)->whereIn('user_id', $friend_ids)->get(['id', 'user_id', 'status'])->keyBy('user_id')->toArray();
]); $chatArr = UsersChatList::where('group_id', $group_id)->whereIn('uid', $friend_ids)->get(['id', 'uid', 'status'])->keyBy('uid')->toArray();
if (!$result) throw new Exception('添加群通知记录失败1'); foreach ($friend_ids as $uid) {
if (!isset($members[$uid])) {//存在聊天群成员记录
$result2 = ChatRecordsInvite::create([ $insertArr[] = ['group_id' => $group_id, 'user_id' => $uid, 'group_owner' => 0, 'status' => 0, 'created_at' => date('Y-m-d H:i:s')];
'record_id' => $result->id, } else if ($members[$uid]['status'] == 1) {
'type' => 1, $updateArr[] = $members[$uid]['id'];
'operate_user_id' => $user_id, }
'user_ids' => implode(',', $friend_ids)
]); if (!isset($chatArr[$uid])) {
$insertArr1[] = ['type' => 2, 'uid' => $uid, 'friend_id' => 0, 'group_id' => $group_id, 'status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
if (!$result2) throw new Exception('添加群通知记录失败2'); } else if ($chatArr[$uid]['status'] == 0) {
$updateArr1[] = $chatArr[$uid]['id'];
Db::commit(); }
} catch (\Exception $e) { }
Db::rollBack();
return [false, 0]; try {
} if ($updateArr) {
UsersGroupMember::whereIn('id', $updateArr)->update(['status' => 0]);
LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $group_id, 0); }
return [true, $result->id];
} if ($insertArr) {
Db::table('users_group_member')->insert($insertArr);
/** }
* 退出群组
* if ($updateArr1) {
* @param int $user_id 用户ID UsersChatList::whereIn('id', $updateArr1)->update(['status' => 1, 'created_at' => date('Y-m-d H:i:s')]);
* @param int $group_id 群组ID }
* @return array
*/ if ($insertArr1) {
public function quit(int $user_id, int $group_id) Db::table('users_chat_list')->insert($insertArr1);
{ }
$record_id = 0;
Db::beginTransaction(); $result = ChatRecord::create([
try { 'msg_type' => 3,
$res = UsersGroupMember::where('group_id', $group_id)->where('user_id', $user_id)->where('group_owner', 0)->update(['status' => 1]); 'source' => 2,
if ($res) { 'user_id' => 0,
UsersChatList::where('uid', $user_id)->where('type', 2)->where('group_id', $group_id)->update(['status' => 0]); 'receive_id' => $group_id,
'created_at' => date('Y-m-d H:i:s')
$result = ChatRecord::create([ ]);
'msg_type' => 3,
'source' => 2, if (!$result) throw new Exception('添加群通知记录失败1');
'user_id' => 0,
'receive_id' => $group_id, $result2 = ChatRecordsInvite::create([
'content' => $user_id, 'record_id' => $result->id,
'created_at' => date('Y-m-d H:i:s') 'type' => 1,
]); 'operate_user_id' => $user_id,
'user_ids' => implode(',', $friend_ids)
if (!$result) { ]);
throw new Exception('添加群通知记录失败 : quitGroupChat');
} if (!$result2) throw new Exception('添加群通知记录失败2');
$result2 = ChatRecordsInvite::create([ Db::commit();
'record_id' => $result->id, } catch (\Exception $e) {
'type' => 2, Db::rollBack();
'operate_user_id' => $user_id, return [false, 0];
'user_ids' => $user_id }
]);
LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $group_id, 0);
if (!$result2) { return [true, $result->id];
throw new Exception('添加群通知记录失败2 : quitGroupChat'); }
}
/**
UsersChatList::where('uid', $user_id)->where('group_id', $group_id)->update(['status' => 0, 'updated_at' => date('Y-m-d H:i:s')]); * 退出群组
*
$record_id = $result->id; * @param int $user_id 用户ID
} * @param int $group_id 群组ID
* @return array
Db::commit(); */
} catch (Exception $e) { public function quit(int $user_id, int $group_id)
Db::rollBack(); {
return [false, 0]; $record_id = 0;
} Db::beginTransaction();
try {
return [true, $record_id]; $res = UsersGroupMember::where('group_id', $group_id)->where('user_id', $user_id)->where('group_owner', 0)->update(['status' => 1]);
} if ($res) {
UsersChatList::where('uid', $user_id)->where('type', 2)->where('group_id', $group_id)->update(['status' => 0]);
/**
* 踢出群组(管理员特殊权限) $result = ChatRecord::create([
* 'msg_type' => 3,
* @param int $group_id 群ID 'source' => 2,
* @param int $user_id 操作用户ID 'user_id' => 0,
* @param array $member_ids 群成员ID 'receive_id' => $group_id,
* @return array 'content' => $user_id,
*/ 'created_at' => date('Y-m-d H:i:s')
public function removeMember(int $group_id, int $user_id, array $member_ids) ]);
{
if (!UsersGroup::isManager($user_id, $group_id)) { if (!$result) {
return [false, 0]; throw new Exception('添加群通知记录失败 : quitGroupChat');
} }
Db::beginTransaction(); $result2 = ChatRecordsInvite::create([
try { 'record_id' => $result->id,
//更新用户状态 'type' => 2,
if (!UsersGroupMember::where('group_id', $group_id)->whereIn('user_id', $member_ids)->where('group_owner', 0)->update(['status' => 1])) { 'operate_user_id' => $user_id,
throw new Exception('修改群成员状态失败'); 'user_ids' => $user_id
} ]);
$result = ChatRecord::create([ if (!$result2) {
'msg_type' => 3, throw new Exception('添加群通知记录失败2 : quitGroupChat');
'source' => 2, }
'user_id' => 0,
'receive_id' => $group_id, UsersChatList::where('uid', $user_id)->where('group_id', $group_id)->update(['status' => 0, 'updated_at' => date('Y-m-d H:i:s')]);
'created_at' => date('Y-m-d H:i:s')
]); $record_id = $result->id;
}
if (!$result) {
throw new Exception('添加群通知记录失败1'); Db::commit();
} } catch (Exception $e) {
Db::rollBack();
$result2 = ChatRecordsInvite::create([ return [false, 0];
'record_id' => $result->id, }
'type' => 3,
'operate_user_id' => $user_id, return [true, $record_id];
'user_ids' => implode(',', $member_ids) }
]);
/**
if (!$result2) { * 踢出群组(管理员特殊权限)
throw new Exception('添加群通知记录失败2'); *
} * @param int $group_id 群ID
* @param int $user_id 操作用户ID
foreach ($member_ids as $member_id) { * @param array $member_ids 群成员ID
UsersChatList::where('uid', $member_id)->where('group_id', $group_id)->update(['status' => 0, 'updated_at' => date('Y-m-d H:i:s')]); * @return array
} */
public function removeMember(int $group_id, int $user_id, array $member_ids)
Db::commit(); {
} catch (Exception $e) { if (!UsersGroup::isManager($user_id, $group_id)) {
Db::rollBack(); return [false, 0];
return [false, 0]; }
}
Db::beginTransaction();
return [true, $result->id]; try {
} //更新用户状态
} if (!UsersGroupMember::where('group_id', $group_id)->whereIn('user_id', $member_ids)->where('group_owner', 0)->update(['status' => 1])) {
throw new Exception('修改群成员状态失败');
}
$result = ChatRecord::create([
'msg_type' => 3,
'source' => 2,
'user_id' => 0,
'receive_id' => $group_id,
'created_at' => date('Y-m-d H:i:s')
]);
if (!$result) {
throw new Exception('添加群通知记录失败1');
}
$result2 = ChatRecordsInvite::create([
'record_id' => $result->id,
'type' => 3,
'operate_user_id' => $user_id,
'user_ids' => implode(',', $member_ids)
]);
if (!$result2) {
throw new Exception('添加群通知记录失败2');
}
foreach ($member_ids as $member_id) {
UsersChatList::where('uid', $member_id)->where('group_id', $group_id)->update(['status' => 0, 'updated_at' => date('Y-m-d H:i:s')]);
}
Db::commit();
} catch (Exception $e) {
Db::rollBack();
return [false, 0];
}
return [true, $result->id];
}
}

View File

@ -1,191 +1,149 @@
<?php <?php
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\UsersFriend;
use App\Model\UsersChatList; use App\Model\UsersFriendsApply;
use App\Model\UsersFriend; use Hyperf\DbConnection\Db;
use App\Model\UsersFriendsApply;
use Hyperf\DbConnection\Db; class UserService extends BaseService
{
class UserService extends BaseService /**
{ * 获取用户信息
/** *
* 获取用户信息 * @param int $user_id 用户ID
* * @param array $field 查询字段
* @param int $user_id 用户ID * @return mixed
* @param array $field 查询字段 */
* @return mixed public function findById(int $user_id, $field = ['*'])
*/ {
public function findById(int $user_id, $field = ['*']) return User::where('id', $user_id)->first($field);
{ }
return User::where('id', $user_id)->first($field);
} /**
* 登录逻辑
/** *
* 登录逻辑 * @param string $mobile 手机号
* * @param string $password 登录密码
* @param string $mobile 手机号 * @return array|bool
* @param string $password 登录密码 */
* @return array|bool public function login(string $mobile, string $password)
*/ {
public function login(string $mobile, string $password) if (!$user = User::where('mobile', $mobile)->first()) {
{ return false;
if (!$user = User::where('mobile', $mobile)->first()) { }
return false;
} if (!password_verify($password, $user->password)) {
return false;
if (!password_verify($password, $user->password)) { }
return false;
} return $user->toArray();
}
return $user->toArray();
} /**
* 账号注册逻辑
/** *
* 账号注册逻辑 * @param array $data 用户数据
* * @return bool
* @param array $data 用户数据 */
* @return bool public function register(array $data)
*/ {
public function register(array $data) Db::beginTransaction();
{ try {
Db::beginTransaction(); $data['password'] = Hash::make($data['password']);
try { $data['created_at'] = date('Y-m-d H:i:s');
$data['password'] = Hash::make($data['password']);
$data['created_at'] = date('Y-m-d H:i:s'); $result = User::create($data);
$result = User::create($data); // 创建用户的默认笔记分类
ArticleClass::create([
// 创建用户的默认笔记分类 'user_id' => $result->id,
ArticleClass::create([ 'class_name' => '我的笔记',
'user_id' => $result->id, 'is_default' => 1,
'class_name' => '我的笔记', 'sort' => 1,
'is_default' => 1, 'created_at' => time()
'sort' => 1, ]);
'created_at' => time()
]); Db::commit();
} catch (\Exception $e) {
Db::commit(); Db::rollBack();
} catch (\Exception $e) { $result = false;
Db::rollBack(); }
$result = false;
} return $result ? true : false;
}
return $result ? true : false;
} /**
* 账号重置密码
/** *
* 账号重置密码 * @param string $mobile 用户手机好
* * @param string $password 新密码
* @param string $mobile 用户手机好 * @return mixed
* @param string $password 新密码 */
* @return mixed public function resetPassword(string $mobile, string $password)
*/ {
public function resetPassword(string $mobile, string $password) return User::where('mobile', $mobile)->update(['password' => Hash::make($password)]);
{ }
return User::where('mobile', $mobile)->update(['password' => Hash::make($password)]);
} /**
* 修改绑定的手机号
/** *
* 修改绑定的手机号 * @param int $user_id 用户ID
* * @param string $mobile 换绑手机号
* @param int $user_id 用户ID * @return array|bool
* @param string $mobile 换绑手机号 */
* @return array|bool public function changeMobile(int $user_id, string $mobile)
*/ {
public function changeMobile(int $user_id, string $mobile) if (User::where('mobile', $mobile)->value('id')) {
{ return [false, '手机号已被他人绑定'];
if (User::where('mobile', $mobile)->value('id')) { }
return [false, '手机号已被他人绑定'];
} $isTrue = (bool)User::where('id', $user_id)->update(['mobile' => $mobile]);
return [$isTrue, null];
$isTrue = (bool)User::where('id', $user_id)->update(['mobile' => $mobile]); }
return [$isTrue, null];
} /**
* 通过手机号查找用户
/** *
* 获取用户所在的群聊 * @param int $friend_id 用户ID
* * @param int $me_user_id 当前登录用户的ID
* @param int $user_id 用户ID * @return array
* @return mixed */
*/ public function getUserCard(int $friend_id,int $me_user_id)
public function getUserChatGroups(int $user_id) {
{ $info = User::select(['id', 'mobile', 'nickname', 'avatar', 'gender', 'motto'])->where('id', $friend_id)->first();
$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']) if(!$info) return [];
->join('users_group', 'users_group.id', '=', 'users_group_member.group_id')
->where([ $info = $info->toArray();
['users_group_member.user_id', '=', $user_id], $info['friend_status'] = 0;//朋友关系状态 0:本人 1:陌生人 2:朋友
['users_group_member.status', '=', 0] $info['nickname_remark'] = '';
]) $info['friend_apply'] = 0;
->orderBy('id', 'desc')->get()->toarray();
// 判断查询信息是否是自己
foreach ($items as $key => $item) { if ($friend_id != $me_user_id) {
// 判断当前用户是否是群主 $friendInfo = UsersFriend::
$items[$key]['isGroupLeader'] = $item['group_user_id'] == $user_id; where('user1', '=', $friend_id > $me_user_id ? $me_user_id :$friend_id)
->where('user2', '=', $friend_id < $me_user_id ? $me_user_id :$friend_id)
//删除无关字段 ->where('status', 1)
unset($items[$key]['group_user_id']); ->first(['id', 'user1', 'user2', 'active', 'user1_remark', 'user2_remark']);
// 是否消息免打扰 $info['friend_status'] = $friendInfo ? 2 : 1;
$items[$key]['not_disturb'] = UsersChatList::where([ if ($friendInfo) {
['uid', '=', $user_id], $info['nickname_remark'] = $friendInfo->user1 == $friend_id ? $friendInfo->user2_remark : $friendInfo->user1_remark;
['type', '=', 2], } else {
['group_id', '=', $item['id']] $res = UsersFriendsApply::where('user_id', $me_user_id)
])->value('not_disturb'); ->where('friend_id', $friend_id)
} ->where('status', 0)
->orderBy('id', 'desc')
return $items; ->exists();
}
$info['friend_apply'] = $res ? 1 : 0;
/** }
* 通过手机号查找用户 }
*
* @param array $where 查询条件 return $info;
* @param int $user_id 当前登录用户的ID }
* @return array }
*/
public function searchUserInfo(array $where, int $user_id)
{
$info = User::select(['id', 'mobile', 'nickname', 'avatar', 'gender', 'motto']);
if (isset($where['uid'])) {
$info->where('id', $where['uid']);
}
if (isset($where['mobile'])) {
$info->where('mobile', $where['mobile']);
}
$info = $info->first();
$info = $info ? $info->toArray() : [];
if ($info) {
$info['friend_status'] = 0;//朋友关系状态 0:本人 1:陌生人 2:朋友
$info['nickname_remark'] = '';
$info['friend_apply'] = 0;
// 判断查询信息是否是自己
if ($info['id'] != $user_id) {
$friend_id = $info['id'];
$friendInfo = UsersFriend::select('id', 'user1', 'user2', 'active', 'user1_remark', 'user2_remark')->where(function ($query) use ($friend_id, $user_id) {
$query->where('user1', '=', $user_id)->where('user2', '=', $friend_id)->where('status', 1);
})->orWhere(function ($query) use ($friend_id, $user_id) {
$query->where('user1', '=', $friend_id)->where('user2', '=', $user_id)->where('status', 1);
})->first();
$info['friend_status'] = $friendInfo ? 2 : 1;
if ($friendInfo) {
$info['nickname_remark'] = ($friendInfo->user1 == $friend_id) ? $friendInfo->user2_remark : $friendInfo->user1_remark;
} else {
$res = UsersFriendsApply::where('user_id', $user_id)->where('friend_id', $info['id'])->where('status', 0)->orderBy('id', 'desc')->exists();
$info['friend_apply'] = $res ? 1 : 0;
}
}
}
return $info;
}
}