22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 1 | package com.example.myproject.service; |
JinGe | fe5140c | 2025-06-06 20:07:42 +0800 | [diff] [blame] | 2 | import cn.dev33.satoken.stp.StpUtil; |
| 3 | import com.example.myproject.entity.FriendRelation; |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 4 | import com.example.myproject.entity.User; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 5 | import com.example.myproject.entity.Users; |
| 6 | import com.example.myproject.entity.UserInviteCode; |
JinGe | fe5140c | 2025-06-06 20:07:42 +0800 | [diff] [blame] | 7 | import com.example.myproject.repository.FriendRelationRepository; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 8 | import com.example.myproject.repository.UserRepository; |
| 9 | import com.example.myproject.repository.UserInviteCodeRepository; |
| 10 | import org.springframework.beans.factory.annotation.Autowired; |
| 11 | import org.springframework.stereotype.Service; |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 12 | import org.springframework.web.multipart.MultipartFile; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 13 | |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 14 | import javax.servlet.http.HttpServletRequest; |
| 15 | import java.io.File; |
| 16 | import java.io.IOException; |
| 17 | import java.nio.file.Files; |
| 18 | import java.nio.file.Path; |
| 19 | import java.nio.file.Paths; |
| 20 | import java.time.LocalDateTime; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 21 | import java.util.*; |
| 22 | |
| 23 | @Service |
| 24 | public class UserService { |
| 25 | |
| 26 | @Autowired |
| 27 | private UserRepository userRepository; |
| 28 | |
| 29 | @Autowired |
| 30 | private UserInviteCodeRepository userInviteCodeRepository; |
| 31 | |
JinGe | fe5140c | 2025-06-06 20:07:42 +0800 | [diff] [blame] | 32 | @Autowired |
| 33 | private FriendRelationRepository friendRelationRepository; |
| 34 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 35 | // 生成邀请码 |
| 36 | public Map<String, Object> generateInviteCode(Long userId) { |
| 37 | // 获取用户信息 |
| 38 | Users user = userRepository.findById(userId).orElse(null); |
| 39 | |
| 40 | // 如果用户不存在,返回错误 |
| 41 | if (user == null) { |
| 42 | Map<String, Object> errorResponse = new HashMap<>(); |
| 43 | errorResponse.put("status", "failure"); |
| 44 | errorResponse.put("message", "用户不存在"); |
| 45 | return errorResponse; |
| 46 | } |
| 47 | |
| 48 | // 检查用户的邀请数量 |
| 49 | if (user.getInviteCount() <= 0) { |
| 50 | Map<String, Object> errorResponse = new HashMap<>(); |
| 51 | errorResponse.put("status", "failure"); |
| 52 | errorResponse.put("message", "没有剩余的邀请码"); |
| 53 | return errorResponse; |
| 54 | } |
| 55 | |
| 56 | // 生成唯一的邀请码 |
| 57 | String inviteCode = generateUniqueInviteCode(); |
| 58 | |
| 59 | // 将邀请码保存到 `user_invite_code` 表 |
| 60 | UserInviteCode userInviteCode = new UserInviteCode(); |
| 61 | userInviteCode.setUserId(userId); |
| 62 | userInviteCode.setInviteCode(inviteCode); |
| 63 | userInviteCode.setCreatedAt(java.time.LocalDateTime.now()); |
| 64 | |
| 65 | userInviteCodeRepository.save(userInviteCode); |
| 66 | |
| 67 | // 更新用户的 `invite_count`,减少1 |
| 68 | user.setInviteCount(user.getInviteCount() - 1); |
| 69 | userRepository.save(user); |
| 70 | |
| 71 | // 返回成功信息 |
| 72 | Map<String, Object> response = new HashMap<>(); |
| 73 | response.put("status", "success"); |
| 74 | response.put("message", "邀请码生成成功"); |
| 75 | response.put("invite_code", inviteCode); |
| 76 | |
| 77 | return response; |
| 78 | } |
| 79 | |
| 80 | // 生成唯一的邀请码,使用26个字母(大小写) |
| 81 | private String generateUniqueInviteCode() { |
| 82 | String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; |
| 83 | StringBuilder inviteCode = new StringBuilder(); |
| 84 | |
| 85 | Random random = new Random(); |
| 86 | for (int i = 0; i < 10; i++) { |
| 87 | inviteCode.append(characters.charAt(random.nextInt(characters.length()))); |
| 88 | } |
| 89 | |
| 90 | return inviteCode.toString(); |
| 91 | } |
| 92 | |
| 93 | public String registerUser(String username, String email, String password, String role, String inviteCode) { |
| 94 | // 检查邮箱是否已经注册 |
| 95 | Optional<Users> existingEmailUser = userRepository.findByEmail(email); |
| 96 | if (existingEmailUser.isPresent()) { |
| 97 | return "该邮箱已被注册"; |
| 98 | } |
| 99 | |
| 100 | // 检查用户名是否已经存在 |
| 101 | Optional<Users> existingUsernameUser = userRepository.findByUsername(username); // 需要根据用户名查询 |
| 102 | if (existingUsernameUser.isPresent()) { |
| 103 | return "该用户名已被注册"; |
| 104 | } |
| 105 | |
| 106 | // 检查邀请码是否有效 |
| 107 | if (inviteCode == null || inviteCode.isEmpty()) { |
| 108 | return "邀请码不能为空"; |
| 109 | } |
| 110 | |
| 111 | Optional<UserInviteCode> invite = userInviteCodeRepository.findByInviteCode(inviteCode); |
| 112 | if (invite.isEmpty() || invite.get().getIsUsed()) { |
| 113 | return "邀请码无效或已被使用"; |
| 114 | } |
| 115 | |
| 116 | // 设置默认等级为2(由于邀请码有效) |
| 117 | Long level = 2L; |
| 118 | |
| 119 | // 设置默认头像 URL |
| 120 | String avatarUrl = "https://example.com/default-avatar.jpg"; // 默认头像 |
| 121 | |
| 122 | // 获取邀请码对应的用户ID |
| 123 | UserInviteCode inviteEntity = invite.get(); |
| 124 | Long inviteUserId = inviteEntity.getUserId(); |
| 125 | |
| 126 | // 创建新用户 |
| 127 | Users newUser = new Users(); |
| 128 | newUser.setUsername(username); |
| 129 | newUser.setEmail(email); |
| 130 | newUser.setPassword(password); |
| 131 | newUser.setRole(role); |
| 132 | newUser.setInviteCount(0); // 初始邀请码数量为 0 |
| 133 | newUser.setLevel(level); |
| 134 | newUser.setAvatarUrl(avatarUrl); // 设置默认头像 |
| 135 | newUser.setRegistrationDate(new java.util.Date()); // 设置注册日期 |
| 136 | newUser.setCurrentExperience(0); // 默认经验为 0 |
| 137 | newUser.setCurrentSeedingHours(0f); // 默认做种时长为 0 |
| 138 | newUser.setRegistrationTime(new java.util.Date()); // 设置注册时间为当前时间 |
| 139 | |
| 140 | // 保存用户信息 |
| 141 | userRepository.save(newUser); |
| 142 | |
JinGe | fe5140c | 2025-06-06 20:07:42 +0800 | [diff] [blame] | 143 | FriendRelation newFriendRelation = new FriendRelation(); |
| 144 | newFriendRelation.setUserId(newUser.getUserId()); |
| 145 | newFriendRelation.setCreateTime(new Date()); |
| 146 | newFriendRelation.setFriendId(inviteUserId); |
| 147 | |
| 148 | FriendRelation newFriendRelations = new FriendRelation(); |
| 149 | newFriendRelations.setUserId(inviteUserId); |
| 150 | newFriendRelations.setCreateTime(new Date()); |
| 151 | newFriendRelations.setFriendId(newUser.getUserId()); |
| 152 | friendRelationRepository.save(newFriendRelation); |
| 153 | friendRelationRepository.save(newFriendRelations); |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 154 | // 更新邀请码的使用状态 |
| 155 | inviteEntity.setIsUsed(true); |
| 156 | userInviteCodeRepository.save(inviteEntity); |
| 157 | |
| 158 | return "用户注册成功"; |
| 159 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 160 | |
| 161 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 162 | public String loginUser(String username, String password) { |
| 163 | // 检查用户是否存在 |
| 164 | Optional<Users> userOptional = userRepository.findByUsername(username); |
| 165 | if (userOptional.isEmpty()) { |
| 166 | return "用户名不存在"; |
| 167 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 168 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 169 | Users user = userOptional.get(); |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 170 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 171 | // 检查密码是否正确 |
| 172 | if (!user.getPassword().equals(password)) { |
| 173 | return "密码错误"; |
| 174 | } |
JinGe | fe5140c | 2025-06-06 20:07:42 +0800 | [diff] [blame] | 175 | StpUtil.login(user.getUserId()); |
| 176 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 177 | // 登录成功 |
| 178 | return "登录成功"; |
| 179 | } |
| 180 | |
| 181 | public String changePassword(Long userId, String oldPassword, String newPassword, String confirmPassword) { |
| 182 | // 查找用户 |
| 183 | Users user = userRepository.findById(userId).orElse(null); |
| 184 | |
| 185 | if (user == null) { |
| 186 | return "用户不存在"; |
| 187 | } |
| 188 | |
| 189 | // 检查旧密码是否正确 |
| 190 | if (!user.getPassword().equals(oldPassword)) { |
| 191 | return "旧密码错误"; |
| 192 | } |
| 193 | |
| 194 | // 检查新密码和确认密码是否一致 |
| 195 | if (!newPassword.equals(confirmPassword)) { |
| 196 | return "新密码与确认密码不一致"; |
| 197 | } |
| 198 | |
| 199 | // 更新密码 |
| 200 | user.setPassword(newPassword); |
| 201 | userRepository.save(user); |
| 202 | |
| 203 | return "密码修改成功"; |
| 204 | } |
| 205 | |
| 206 | // 获取用户个人资料 |
| 207 | public Map<String, Object> getProfile(Long userId) { |
| 208 | Optional<Users> userOptional = userRepository.findById(userId); |
| 209 | |
| 210 | // 如果用户不存在,返回null或者可以抛出异常 |
| 211 | if (userOptional.isEmpty()) { |
| 212 | return null; // 可以返回 null 或者根据需要返回错误信息 |
| 213 | } |
| 214 | |
| 215 | Users user = userOptional.get(); |
| 216 | |
| 217 | // 将需要的字段放入 Map 中 |
| 218 | Map<String, Object> profile = new LinkedHashMap<>(); |
| 219 | profile.put("avatarUrl", user.getAvatarUrl()); |
| 220 | profile.put("username", user.getUsername()); |
| 221 | profile.put("email", user.getEmail()); |
| 222 | profile.put("gender", user.getGender()); |
| 223 | profile.put("description", user.getDescription()); |
| 224 | profile.put("hobbies", user.getHobbies()); |
| 225 | profile.put("level", user.getLevel()); |
| 226 | profile.put("Experience", user.getCurrentExperience()); |
| 227 | profile.put("uploadCount", user.getUploadCount()); |
| 228 | profile.put("downloadCount", user.getDownloadCount()); |
| 229 | profile.put("shareRate", user.getShareRate()); |
| 230 | profile.put("registrationTime", user.getRegistrationTime()); |
| 231 | |
| 232 | return profile; |
| 233 | } |
| 234 | |
| 235 | // 修改用户个人资料 |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 236 | public boolean editProfile(Long userId, String nickname, String gender, String description, String hobbies) { |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 237 | Optional<Users> userOptional = userRepository.findById(userId); |
| 238 | |
| 239 | // 如果用户不存在,返回false |
| 240 | if (userOptional.isEmpty()) { |
| 241 | return false; // 用户不存在 |
| 242 | } |
| 243 | |
| 244 | Users user = userOptional.get(); |
| 245 | |
| 246 | // 更新用户资料,只有传入值才会更新对应字段 |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 247 | if (nickname != null) { |
| 248 | user.setUsername(nickname); |
| 249 | } |
| 250 | if (gender != null) { |
| 251 | user.setGender(gender); |
| 252 | } |
| 253 | if (description != null) { |
| 254 | user.setDescription(description); |
| 255 | } |
| 256 | if (hobbies != null) { |
| 257 | user.setHobbies(hobbies); |
| 258 | } |
| 259 | |
| 260 | // 保存更新后的用户信息 |
| 261 | userRepository.save(user); |
| 262 | |
| 263 | return true; // 更新成功 |
| 264 | } |
| 265 | |
| 266 | public Map<String, Object> calculateShareRate(Long userId) { |
| 267 | // 查找用户 |
| 268 | Users user = userRepository.findById(userId).orElse(null); |
| 269 | if (user == null) { |
| 270 | return Map.of("status", "error", "message", "用户不存在"); |
| 271 | } |
| 272 | |
| 273 | // 获取上传量和下载量 |
| 274 | Float uploadCount = user.getUploadCount(); |
| 275 | Float downloadCount = user.getDownloadCount(); |
| 276 | |
| 277 | // 计算分享率 |
| 278 | Float shareRate = 0f; // 默认分享率为0 |
| 279 | if (downloadCount != 0) { |
| 280 | shareRate = uploadCount / downloadCount; // 分享率 = 上传量 / 下载量 |
| 281 | } |
| 282 | |
| 283 | // 更新用户的分享率 |
| 284 | user.setShareRate(shareRate); |
| 285 | userRepository.save(user); |
| 286 | |
| 287 | // 返回结果 |
| 288 | return Map.of("status", "success", "message", "分享率计算成功", "shareRate", shareRate); |
| 289 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 290 | |
| 291 | |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 292 | private static final String AVATAR_DIR = "uploads/avatarUrl/"; |
| 293 | |
| 294 | public Map<String, Object> uploadUserAvatar(Long userId, MultipartFile file) { |
| 295 | Users user = userRepository.findById(userId) |
| 296 | .orElseThrow(() -> new RuntimeException("用户不存在")); |
| 297 | |
| 298 | try { |
| 299 | String avatarUrl = saveAvatar(file, userId); |
| 300 | user.setAvatarUrl(avatarUrl); |
| 301 | userRepository.save(user); |
| 302 | |
| 303 | Map<String, Object> response = new HashMap<>(); |
| 304 | response.put("status", "success"); |
| 305 | response.put("message", "头像上传成功"); |
| 306 | response.put("userId", user.getUserId()); |
| 307 | response.put("avatarUrl", avatarUrl); |
| 308 | return response; |
| 309 | |
| 310 | } catch (IOException e) { |
| 311 | throw new RuntimeException("头像上传失败: " + e.getMessage()); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | // 保存头像文件并返回可访问 URL |
| 316 | public String saveAvatar(MultipartFile file, Long userId) throws IOException { |
| 317 | String originalFilename = file.getOriginalFilename(); |
| 318 | String extension = originalFilename.substring(originalFilename.lastIndexOf('.')); |
| 319 | String fileName = userId + extension; // 以用户ID作为文件名 |
| 320 | Path path = Paths.get(AVATAR_DIR + fileName); |
| 321 | Files.createDirectories(path.getParent()); |
| 322 | Files.write(path, file.getBytes()); |
| 323 | return "/" + AVATAR_DIR + fileName; // 返回相对URL路径 |
| 324 | } |
| 325 | |
| 326 | |
| 327 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 328 | } |