live-forum/server/webapi/LiveForum/LiveForum.Service/Users/UsersInfoService.cs
2026-03-24 11:27:37 +08:00

339 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using FreeSql;
using LiveForum.Code.Base;
using LiveForum.Code.JwtInfrastructure;
using LiveForum.IService.Users;
using LiveForum.Model;
using LiveForum.Model.Dto.Base;
using LiveForum.Model.Dto.Others;
using LiveForum.Model.Dto.Users;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiveForum.Service.Users
{
public class UsersInfoService : IUsersInfoService
{
private readonly JwtUserInfoModel _userInfoModel;
private readonly IBaseRepository<T_Users> _userRepository;
private readonly IBaseRepository<T_UserLevels> _userLevelsRepository;
private readonly IBaseRepository<T_UserCertifications> _userCertificationsRepository;
private readonly IBaseRepository<T_Posts> _postsRepository;
private readonly IBaseRepository<T_Comments> _commentsRepository;
private readonly IBaseRepository<T_Follows> _followsRepository;
private readonly IBaseRepository<T_Likes> _likesRepository;
private readonly LiveForum.IService.Others.ICertificationTypesService _certificationTypesService;
private readonly IOptionsSnapshot<AppSettings> _appSettingsSnapshot;
private readonly IUserInfoService _userInfoService;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="userInfoModel">JWT用户信息模型</param>
/// <param name="userRepository">用户仓储</param>
/// <param name="userLevelsRepository">用户等级仓储</param>
/// <param name="userCertificationsRepository">用户认证仓储</param>
/// <param name="postsRepository">帖子仓储</param>
/// <param name="commentsRepository">评论仓储</param>
/// <param name="followsRepository">关注仓储</param>
/// <param name="likesRepository">点赞仓储</param>
/// <param name="certificationTypesService">认证类型服务</param>
/// <param name="appSettingsSnapshot">应用设置(支持热更新)</param>
/// <param name="userInfoService">用户信息服务</param>
public UsersInfoService(
JwtUserInfoModel userInfoModel,
IBaseRepository<T_Users> userRepository,
IBaseRepository<T_UserLevels> userLevelsRepository,
IBaseRepository<T_UserCertifications> userCertificationsRepository,
IBaseRepository<T_Posts> postsRepository,
IBaseRepository<T_Comments> commentsRepository,
IBaseRepository<T_Follows> followsRepository,
IBaseRepository<T_Likes> likesRepository,
LiveForum.IService.Others.ICertificationTypesService certificationTypesService,
IOptionsSnapshot<AppSettings> appSettingsSnapshot,
IUserInfoService userInfoService)
{
_userInfoModel = userInfoModel;
_userRepository = userRepository;
_userLevelsRepository = userLevelsRepository;
_userCertificationsRepository = userCertificationsRepository;
_postsRepository = postsRepository;
_commentsRepository = commentsRepository;
_followsRepository = followsRepository;
_likesRepository = likesRepository;
_certificationTypesService = certificationTypesService;
_appSettingsSnapshot = appSettingsSnapshot;
_userInfoService = userInfoService;
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<GetUserInfoRespDto>> GetUserInfo()
{
var userId = (long)_userInfoModel.UserId;
// 1. 获取用户基本信息
var user = await _userRepository.Select
.Where(x => x.Id == userId)
.FirstAsync();
if (user == null)
{
return new BaseResponse<GetUserInfoRespDto>(ResponseCode.Error, "用户不存在");
}
// 2. 获取用户等级信息
var userLevel = await _userLevelsRepository.Select
.Where(x => x.Id == user.LevelId)
.FirstAsync();
// 3. 统计用户数据
var postCount = await _postsRepository.Select
.Where(x => x.UserId == userId && !x.IsDeleted)
.CountAsync();
var commentCount = await _commentsRepository.Select
.Where(x => x.UserId == userId && !x.IsDeleted)
.CountAsync();
var followingCount = await _followsRepository.Select
.Where(x => x.FollowerId == userId)
.CountAsync();
var followerCount = await _followsRepository.Select
.Where(x => x.FollowedUserId == userId)
.CountAsync();
var totalLikes = await _likesRepository.Select
.Where(x => x.UserId == userId)
.CountAsync();
// 4. 获取认证类型信息使用基础接口直接返回DTO
CertificationTypeDto certifiedTypeDto = null;
if (user.CertifiedType.HasValue && user.CertifiedType.Value > 0)
{
certifiedTypeDto = await _certificationTypesService.GetCertificationTypeByIdBase(user.CertifiedType.Value);
}
// 5. 获取默认头像(如果用户头像为空)
var avatar = user.Avatar;
if (string.IsNullOrEmpty(avatar))
{
var appSettings = _appSettingsSnapshot.Value;
avatar = string.IsNullOrEmpty(appSettings.UserDefaultIcon)
? ""
: appSettings.UserDefaultIcon;
user.Avatar = avatar;
_userRepository.Update(user);
}
// 5.1 检查并生成UID如果为空
if (string.IsNullOrEmpty(user.UID))
{
user.UID = await _userInfoService.GenerateUniqueUIDAsync();
user.UpdatedAt = DateTime.Now;
await _userRepository.UpdateAsync(user);
}
// 6. 构建返回数据
var result = new GetUserInfoRespDto
{
UserId = (int)user.Id,
NickName = user.NickName,
Avatar = avatar,
Gender = user.Gender ?? 0,
Birthday = user.Birthday?.ToString("yyyy-MM-dd"),
Signature = user.Signature,
IsVip = user.IsVip,
VipExpireTime = user.VipExpireTime,
CertifiedType = certifiedTypeDto,
CertifiedStatus = user.CertifiedStatus,
LevelId = user.LevelId,
LevelName = userLevel?.LevelName,
Experience = user.Experience,
PostCount = (int)postCount,
CommentCount = (int)commentCount,
FollowingCount = (int)followingCount,
FollowerCount = (int)followerCount,
TotalLikes = (int)totalLikes,
UID = user.UID ?? "",
IsMinor = user.IsMinor
};
return new BaseResponse<GetUserInfoRespDto>(result);
}
/// <summary>
/// 修改用户信息
/// </summary>
/// <param name="updateUserReq"></param>
/// <returns></returns>
public async Task<BaseResponseBool> UpdateUserInfo(UpdateUserInfoReq updateUserReq)
{
var userId = (long)_userInfoModel.UserId;
// 1. 获取用户信息
var user = await _userRepository.Select
.Where(x => x.Id == userId)
.FirstAsync();
if (user == null)
{
return new BaseResponseBool { Code = ResponseCode.Error, Message = "用户不存在" };
}
// 2. 更新用户信息
user.NickName = updateUserReq.NickName ?? user.NickName;
user.Avatar = updateUserReq.Avatar ?? user.Avatar;
user.Gender = (int?)updateUserReq.Gender;
if (!string.IsNullOrEmpty(updateUserReq.birthday) && DateTime.TryParse(updateUserReq.birthday, out var birthday))
{
user.Birthday = birthday;
}
user.Signature = updateUserReq.signature ?? user.Signature;
user.UpdatedAt = DateTime.Now;
// 3. 保存到数据库
await _userRepository.UpdateAsync(user);
return new BaseResponseBool { Code = ResponseCode.Success, Data = true };
}
/// <summary>
/// 获取用户等级列表
/// </summary>
/// <returns></returns>
public async Task<BaseResponseList<GetUserLevelsRespDto>> GetUserLevels()
{
var levels = await _userLevelsRepository.Select
.Where(x => x.IsActive)
.OrderBy(x => x.MinExperience)
.ToListAsync();
var result = levels.Select(level => new GetUserLevelsRespDto
{
LevelId = level.Id,
LevelName = level.LevelName,
MinExperience = level.MinExperience,
MaxExperience = level.MaxExperience,
LevelIcon = level.LevelIcon,
LevelColor = level.LevelColor,
Privileges = ParsePrivileges(level.Privileges)
}).ToList();
return new BaseResponseList<GetUserLevelsRespDto> { Code = ResponseCode.Success, Data = result };
}
/// <summary>
/// 提交认证申请
/// </summary>
/// <param name="userCertifications"></param>
/// <returns></returns>
public async Task<BaseResponseBool> Certifications(UserCertificationsReq userCertifications)
{
var userId = (long)_userInfoModel.UserId;
//if (!(userInfo.CertifiedStatus == null || userInfo.CertifiedStatus == Model.Enum.Users.CertifiedStatusEnum.未认证))
//{
// return new BaseResponseBool { Code = ResponseCode.Error, Message = "您已有待审核的认证申请,请勿重复提交" };
//}
// 1. 检查是否已有待审核的认证申请
var existingCertification = await _userCertificationsRepository.Select
.Where(x => x.UserId == userId && x.Status == 0) // 0-待审核
.FirstAsync();
if (existingCertification != null)
{
return new BaseResponseBool { Code = ResponseCode.UserNotCertified, Message = "您已有待审核的认证申请,请勿重复提交" };
}
// 2. 创建认证申请
var certification = new T_UserCertifications
{
UserId = userId,
CertificationType = 0,
DouyinId = userCertifications.DouyinId ?? "",
ContactInfo = userCertifications.ContactInfo ?? "",
VideoUrl = userCertifications.VideoUrl ?? "",
FanLevel = userCertifications.FanLevel,
Status = 0, // 0-待审核
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
var userInfo = await _userRepository.Where(it => it.Id == userId).FirstAsync();
userInfo.CertifiedStatus = Model.Enum.Users.CertifiedStatusEnum.;
await _userCertificationsRepository.InsertAsync(certification);
await _userRepository.UpdateAsync(userInfo);
return new BaseResponseBool { Code = ResponseCode.Success, Data = true };
}
/// <summary>
/// 获取用户认证记录
/// </summary>
/// <returns></returns>
public async Task<BaseResponseList<UserCertificationsReq>> GetUserCertifications(BaseRequestPage page)
{
var userId = (long)_userInfoModel.UserId;
var certifications = await _userCertificationsRepository.Select
.Where(x => x.UserId == userId)
.OrderByDescending(x => x.CreatedAt)
.Skip((page.PageIndex - 1) * page.PageSize)
.Take(page.PageSize)
.ToListAsync();
var result = certifications.Select(cert => new UserCertificationsReq
{
UserId = (int)cert.UserId,
CertificationType = cert.CertificationType,
DouyinId = cert.DouyinId,
ContactInfo = cert.ContactInfo,
VideoUrl = cert.VideoUrl,
FanLevel = cert.FanLevel ?? 0
}).ToList();
return new BaseResponseList<UserCertificationsReq> { Code = ResponseCode.Success, Data = result };
}
/// <summary>
/// 解析等级权限JSON
/// </summary>
/// <param name="privilegesJson"></param>
/// <returns></returns>
private UserLevelsPrivileges? ParsePrivileges(string? privilegesJson)
{
if (string.IsNullOrEmpty(privilegesJson))
{
return new UserLevelsPrivileges
{
MaxPostsPerDay = 5,
CanComment = true
};
}
try
{
return System.Text.Json.JsonSerializer.Deserialize<UserLevelsPrivileges>(privilegesJson);
}
catch
{
return new UserLevelsPrivileges
{
MaxPostsPerDay = 5,
CanComment = true
};
}
}
}
}