using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Datory.Utils;
using GxPress.Api.Tools;
using GxPress.Auth;
using GxPress.Common.Exceptions;
using GxPress.Common.Tools;
using GxPress.Common.Validation;
using GxPress.Entity;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.Friends;
using GxPress.Request.AddressBookGroup;
using GxPress.Request.AddressBookGroupUser;
using GxPress.Request.App.User;
using GxPress.Request.Department;
using GxPress.Request.Feedback;
using GxPress.Request.User;
using GxPress.Result.AddressBook;
using GxPress.Result.AddressBookGroupUser;
using GxPress.Result.App.FileLibrary;
using GxPress.Result.App.User;
using GxPress.Result.Department;
using GxPress.Result.User;
using GxPress.Service.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using GxPress.Service.Interface.Department;
using GxPress.Request.UserMiddle;
using GxPress.Service.Interface.UserMiddle;
using System.Linq;
using AutoMapper;
namespace GxPress.Api.WebControllers
{
///
/// 导航
///
[Route("api/web/user")]
[ApiController]
[Authorize]
public class UserController : Controller
{
private readonly JwtOptions _jwtOptions;
private readonly ILogger _logger;
private readonly IUserRepository _userRepository;
private readonly IDepartmentService departmentService;
private readonly IDepartmentRepository _departmentRepository;
private readonly ILoginContext _loginContext;
private readonly IUserService _userService;
private readonly IFileLibraryRepository fileLibraryRepository;
private readonly IDistributedCache _cache;
private readonly IUserLoginRepository userLoginRepository;
private readonly IAddressBookGroupRepository addressBookGroupRepository;
private readonly IAddressBookGroupUserRepository _addressBookGroupUserRepository;
private readonly IFeedbackRepository _feedbackRepository;
private readonly IFriendsRepository friendsRepository;
private readonly IUserMiddleService userMiddleService;
private readonly IMapper _mapper;
public UserController(IUserRepository userRepository, IOptions jwtOptions,
ILogger logger, IDepartmentRepository departmentRepository, ILoginContext loginContext,
IUserService userService, IFileLibraryRepository fileLibraryRepository, IDistributedCache cache, IUserLoginRepository userLoginRepository, IAddressBookGroupRepository addressBookGroupRepository, IAddressBookGroupUserRepository _addressBookGroupUserRepository, IFeedbackRepository _feedbackRepository, IFriendsRepository friendsRepository, IDepartmentService departmentService, IUserMiddleService userMiddleService, IMapper _mapper)
{
_userRepository = userRepository;
_departmentRepository = departmentRepository;
_userService = userService;
_jwtOptions = jwtOptions.Value;
_logger = logger;
_loginContext = loginContext;
this.fileLibraryRepository = fileLibraryRepository;
_cache = cache;
this.userLoginRepository = userLoginRepository;
this.addressBookGroupRepository = addressBookGroupRepository;
this._addressBookGroupUserRepository = _addressBookGroupUserRepository;
this._feedbackRepository = _feedbackRepository;
this.friendsRepository = friendsRepository;
this.departmentService = departmentService;
this.userMiddleService = userMiddleService;
this._mapper = _mapper;
}
///
/// 登录
///
///
///
[HttpPost("signin")]
[AllowAnonymous]
public async Task SignIn(UserSignInRequest request)
{
var result = await _userRepository.SignInAsync(request);
//记录登录
await userLoginRepository.InsertAsync(new UserLogin { UserId = result.UserId });
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString()),
new Claim(ClaimTypes.Actor, result.User.Name.ToString())
};
result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
return result;
}
///
/// 绑定opendId
///
///
///
[HttpPost("set-opend-Id")]
[AllowAnonymous]
public async Task SetOpenId(UserSignInRequest request)
{
var success = await _userRepository.UpdateByOpendIdAsync(request);
if (success)
{
var result = await _userRepository.SignInAsync(request);
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString())
};
result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
return result;
}
return new UserSignInResult();
}
///
/// 查询opendId是否存在
///
///
///
[HttpGet("find-opend-Id/{opendId}")]
[AllowAnonymous]
public async Task FindOpenId(string opendId)
{
var user = await _userRepository.GetByOpenIdAsync(opendId);
if (user == null)
return false;
return true;
}
///
/// 登录验证码发送
///
///
///
[HttpGet("sendSmsCode")]
[AllowAnonymous]
public async Task SendSmsCode([FromQuery][Required][Mobile] string phone)
{
var user = await _userRepository.GetByPhoneAsync(phone);
//用户不存在
if (user == null)
throw new BusinessException("该用户不存在");
//发送短信
var key = $"login:{phone}";
var code = await _cache.GetStringAsync(key);
if (!string.IsNullOrEmpty(code))
throw new BusinessException("请求太频繁!");
code = RandomGenerator.GetNumberString(6);
code="123456";
if (Common.Sms.AliySms.SendSms(phone, code))
{
_logger.LogInformation("{phone}验证码:{code}", phone, code);
var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
});
return true;
}
return false;
}
///
/// 更换手机号码验证码发送
///
///
///
[HttpGet("send-sms-code")]
public async Task SendSmsCodeReplace([FromQuery][Required][Mobile] string phone)
{
var user = await _userRepository.GetByPhoneAsync(phone);
if (user != null)
throw new BusinessException("号码以被使用");
//发送短信
var key = $"login:{phone}";
var code = await _cache.GetStringAsync(key);
if (!string.IsNullOrEmpty(code))
throw new BusinessException("请求太频繁!");
code = RandomGenerator.GetNumberString(6);
if (Common.Sms.AliySms.SendSms(phone, code))
{
_logger.LogInformation("{phone}验证码:{code}", phone, code);
var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
});
return true;
}
return false;
}
///
/// app查询用户详情
///
///
[HttpGet("detail")]
public async Task GetDetail()
{
var id = _loginContext.AccountId;
var user = await _userRepository.GetAsync(id);
if (user == null)
throw new BusinessException("用户id有误");
return await _userRepository.GetDetailAsync(id);
}
///
/// app查询他人用户详情
///
///
[HttpGet("detail/{id}")]
public async Task GetDetail(int id)
{
if (id <= 0)
throw new BusinessException("用户id有误");
return await _userService.GetUserByIdAsync(_loginContext.AccountId, id);
}
///
/// app更新用户信息
///
///
///
[HttpPut("update")]
public async Task Update([FromBody] UserInfoRequest request)
{
var id = _loginContext.AccountId;
var result = await _userService.UpdateAsync(id, request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 私信
///
///
[HttpPost("update-user-private-letter")]
public async Task UpdateUserPrivateLetter()
{
UserPrivateLetterRequest request = new UserPrivateLetterRequest { Id = _loginContext.AccountId };
var result = await _userRepository.UpdateUserPrivateLetterAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 通知
///
///
[HttpPost("update-user-notice")]
public async Task UpdateUserNotice()
{
var request = new UserNoticeRequest { Id = _loginContext.AccountId };
var result = await _userRepository.UpdateUserNoticeAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 回复
///
///
[HttpPost("update-user-reply")]
public async Task UpdateUserReply()
{
var request = new UserReplyRequest { Id = _loginContext.AccountId };
var result = await _userRepository.UpdateUserReplyAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 静音
///
///
[HttpPost("update-user-mute")]
public async Task UpdateUserMute()
{
var request = new UserMuteRequest { Id = _loginContext.AccountId };
var result = await _userRepository.UpdateUserMuteAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 震动
///
///
[HttpPost("update-user-shake")]
public async Task UpdateUserShake()
{
var request = new UserShakeRequest { Id = _loginContext.AccountId };
var result = await _userRepository.UpdateUserShakeAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 用户修改手机号码
///
///
///
[HttpPost("update-user-phone")]
public async Task UpdateUserPhone(UserUpdatePhoneRequest request)
{
request.UserId = _loginContext.AccountId;
var result = await _userRepository.UpdateUserPhoneAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 邮箱验证码
///
///
///
[HttpPost("send-email-verify-code")]
public async Task SendEmailVerifyCode(UserEmailVerifyCodeRequest request)
{
request.UserId = _loginContext.AccountId;
var result = await _userRepository.SendEmailVerifyCodeAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 修改邮箱
///
///
///
[HttpPost("update-user-email")]
public async Task UpdateUserEmail(UserUpdateEmailRequest request)
{
request.UserId = _loginContext.AccountId;
var result = await _userRepository.UpdateUserEmailAsync(request);
if (result == false)
throw new BusinessException("更新失败");
return true;
}
///
/// 查询联系人
///
///
///
[HttpPost("search")]
public async Task> SearchUserName(SearchUserNameRequest request)
{
return await _userService.GetSearchUserInfoResults(_loginContext.AccountId, request.Key);
}
///
/// 根据部门ID获取自建ID获取用户列表
///
///
///
[HttpPost("find")]
public async Task> FindUser(FindUserRequest request)
{
request.UserId = _loginContext.AccountId;
return await _userService.FindUser(request);
}
///
/// 根据部门ID获取自建ID获取用户列表
///
///
///
[HttpGet("find-name")]
public async Task> FindUserByName([FromQuery] string name)
{
return await _userRepository.UserByNameAsync(name);
}
///
/// 根据GUID查询用户
///
///
[HttpPost("guid")]
public async Task FindUserByGuid(FindUserByGuidRequest request)
{
var user = await _userRepository.GetGuidAsync(request.Guid);
return user;
}
///
/// 获取用户工作模块未读数据
///
///
[HttpGet("user-uread-count")]
public async Task GetUserCountAsync()
{
return await _userService.GetUserCountAsync(_loginContext.AccountId);
}
///
/// 根据用户名获取电脑上传的数据
///
///
[HttpGet("user-file-library")]
public async Task> GetFileLibraryByUserIdAsync()
{
return await fileLibraryRepository.GetFileLibraryByUserIdAsync(_loginContext.AccountId);
}
///
/// 获取用户通讯录组
///
///
[HttpPost("list-group")]
public async Task GetAddressBookList()
{
var request = new AddressBookListRequest { UserId = _loginContext.AccountId };
return await addressBookGroupRepository.GetAddressBookListAsync(request);
}
///
/// 获取自建用户
///
///
///
[HttpPost("list")]
public async Task GetAddressBookGroupUserList(
AddressBookGroupUserSearchRequest request)
{
var userId = _loginContext.AccountId;
return await _addressBookGroupUserRepository.GetAddressBookGroupUserListAsync(request, userId);
}
///
/// 根据部门ID获取成员以及下级部门
///
///
///
[HttpPost("user-list")]
public async Task GetDepartmentUserResult(DepartmentUserRequest request)
{
request.UserId = _loginContext.AccountId;
return await departmentService.GetDepartmentUserResultAsync(request);
}
///
/// 添加意见反馈
///
///
/// ///
[HttpPut("add-feedback")]
public async Task Add([FromBody] FeedbackInRequest request)
{
request.UserId = _loginContext.AccountId;
var feedback = new Feedback
{
UserId = request.UserId,
Content = request.Content,
FeedbackType = request.FeedbackType
};
return await _feedbackRepository.InsertAsync(feedback) > 0;
}
///
/// 获取用户的通讯录
///
///
[HttpGet("user-link")]
public async Task GetUserLinkResultAsync()
{
return await _userService.GetUserLinkResultAsync(_loginContext.AccountId);
}
///
/// 查询不是好友的用户
///
///
[HttpGet("find-friends/{keyword}")]
public async Task> FindUserInfoNoFriendsResultAsync(string keyword)
{
return await _userService.FindUserInfoNoFriendsResultAsync(_loginContext.AccountId, keyword);
}
///
/// 删除我的好友
///
///
[HttpDelete("friends")]
public async Task DeleteAsync(IEnumerable friendsIds)
{
return await friendsRepository.DeleteAsync(friendsIds, _loginContext.AccountId);
}
///
/// 根据部门ID获取用户
///
/// ///
///
[HttpGet("departent/{departentId}")]
public async Task> GetUserInfoByDepartentResult(int departentId)
{
return await _userService.GetUserInfoByDepartentResult(departentId);
}
///
/// 获取群聊和小组的用户
///
///
///
[HttpPost("group-chat")]
public async Task> GetGroupOrGroupChatUserInfosResult(UserInfoByGroupoRoGroupChatResult request)
{
request.UserId = _loginContext.AccountId;
return await _userService.GetGroupOrGroupChatUserInfosResult(request);
}
///
/// 获取用户列表
///
/// 来源类型 1:通知收件人 2:通知抄送人 3:站内信收集人 4:站内信抄送人 5:话题 6:笔记共享文件夹 7:收藏共享文件夹
///
[HttpPost("user-middle")]
public async Task> FindUsersAsync(UserMiddles userMiddles)
{
var model = await userMiddleService.FindUsersAsync(userMiddles.Item, _loginContext.AccountId);
var result = model.Select(n => _mapper.Map(n)).ToList();
foreach (var item in result)
{
item.TypeId = 0;
item.TypeValue = 0;
}
return result;
}
}
}