注册登录,用户等级,社交,动态,新手任务
Change-Id: I1d3183526517fb3c0dab665e0e7547eefa5c9d76
diff --git a/src/main/java/com/example/myproject/service/PostService.java b/src/main/java/com/example/myproject/service/PostService.java
new file mode 100644
index 0000000..515de78
--- /dev/null
+++ b/src/main/java/com/example/myproject/service/PostService.java
@@ -0,0 +1,270 @@
+package com.example.myproject.service;
+
+import com.example.myproject.entity.Likes;
+import com.example.myproject.entity.Post;
+import com.example.myproject.entity.Users;
+import com.example.myproject.repository.CollectionsRepository;
+import com.example.myproject.repository.LikesRepository;
+import com.example.myproject.repository.PostRepository;
+import com.example.myproject.repository.UserRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+import com.example.myproject.entity.Collections;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+
+@Service
+public class PostService {
+
+ @Autowired
+ private PostRepository postRepository;
+
+ @Autowired
+ private UserRepository userRepository;
+ @Autowired
+ private LikesRepository likesRepository;
+
+ @Autowired
+ private CollectionsRepository collectionsRepository;
+
+ private static final String IMAGE_DIR = "uploads/post/";
+
+
+ //创建帖子
+ public Map<String, Object> createPost(Long userId, String postContent, String title, MultipartFile[] imageFiles) {
+ // 查找用户信息
+ Users user = userRepository.findById(Long.valueOf(userId)).orElseThrow(() -> new RuntimeException("User not found"));
+ Post post = new Post();
+ post.setUser_id(user.getUserId());
+ post.setPostTime(new Date());
+ post.setPostLikeNum(0);
+ post.setPostCollectNum(0);
+ post.setPostContent(postContent);
+ post.setTitle(title);
+
+ // 处理多张图片的上传
+ StringBuilder imageUrlsBuilder = new StringBuilder();
+ if (imageFiles != null && imageFiles.length > 0) {
+ for (int i = 0; i < imageFiles.length; i++) {
+ if (i > 0) {
+ imageUrlsBuilder.append(",");
+ }
+ try {
+ String imageUrl = saveImage(imageFiles[i]);
+ imageUrlsBuilder.append(imageUrl);
+ } catch (IOException e) {
+ throw new RuntimeException("Image upload failed: " + e.getMessage());
+ }
+ }
+ }
+ post.setImageUrl(imageUrlsBuilder.toString());
+ Post savedPost = postRepository.save(post);
+ Map<String, Object> response = new HashMap<>();
+ response.put("postNo", savedPost.getPostNo());
+ response.put("message", "帖子创建成功");
+ return response;
+ }
+
+ // 保存图片并返回图片的 URL
+ public String saveImage(MultipartFile imageFile) throws IOException {
+ String fileName = imageFile.getOriginalFilename();
+ Path path = Paths.get(IMAGE_DIR + fileName);
+ Files.createDirectories(path.getParent());
+ Files.write(path, imageFile.getBytes());
+ return "/images/" + fileName;
+ }
+
+
+ //编辑帖子
+ public void updatePost(Long postId, Post post) {
+ Post existingPost = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
+ if (post.getTitle() != null) {
+ existingPost.setTitle(post.getTitle());
+ }
+ if (post.getPostContent() != null) {
+ existingPost.setPostContent(post.getPostContent());
+ }
+ if (post.getImageUrl() != null) {
+ existingPost.setImageUrl(post.getImageUrl());
+ }
+ existingPost.setPostTime(post.getPostTime());
+ // 保存更新后的帖子
+ postRepository.save(existingPost);
+ }
+
+ //删除帖子
+ public void deletePost(Long postId) {
+ // 查找指定 ID 的帖子,如果不存在则抛出异常
+ if (!postRepository.existsById(postId)) {
+ throw new RuntimeException("Post not found");
+ }
+ // 删除该帖子
+ postRepository.deleteById(postId);
+ }
+
+ //点赞帖子(已完成)
+ public void likePost(Long postId, Long userId) {
+ // 查找指定 ID 的帖子
+ Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
+ post.setPostLikeNum(post.getPostLikeNum() + 1);
+
+ // 保存帖子
+ postRepository.save(post);
+ Likes like = new Likes();
+ like.setUserId(userId);
+ like.setPostNo(postId);
+ // 保存点赞记录
+ likesRepository.save(like);
+ }
+
+ // 取消点赞帖子(已完成)
+ public void unlikePost(Long postId, Long userId) {
+ // 查找指定 ID 的帖子
+ Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
+
+ // 如果点赞数大于 0,则减少点赞数
+ if (post.getPostLikeNum() > 0) {
+ post.setPostLikeNum(post.getPostLikeNum() - 1);
+ }
+
+ // 删除点赞表中对应的记录
+ likesRepository.deleteLikeByUserIdAndPostNo(userId, postId);
+
+ // 保存更新后的帖子
+ postRepository.save(post);
+ }
+
+
+ // 获取帖子列表(已完成)
+ public Map<String, Object> getAllPosts() {
+ List<Post> posts = postRepository.findAll();
+ List<Map<String, Object>> postList = new ArrayList<>();
+
+ for (Post post : posts) {
+ Map<String, Object> postMap = new LinkedHashMap<>();
+ postMap.put("postNo", post.getPostNo());
+ postMap.put("user_id", post.getUser_id());
+ postMap.put("postContent", post.getPostContent());
+ postMap.put("imgUrl", post.getImageUrl());
+ postMap.put("title", post.getTitle());
+ postMap.put("createdAt", post.getPostTime().toString());
+ postMap.put("likeCount", post.getPostLikeNum());
+ postMap.put("collectCount", post.getPostCollectNum());
+
+ postList.add(postMap);
+ }
+
+ Map<String, Object> response = new HashMap<>();
+ // 统计帖子数量
+ response.put("total", postList.size());
+ response.put("posts", postList);
+
+ return response;
+ }
+
+ public Map<String, Object> getPostById(Long postId) {
+ // 获取帖子
+ Optional<Post> postOptional = postRepository.findById(postId);
+
+ // 如果帖子存在
+ if (postOptional.isPresent()) {
+ Post post = postOptional.get();
+ Map<String, Object> postData = new LinkedHashMap<>();
+ postData.put("postNo", post.getPostNo());
+ postData.put("user_id", post.getUser_id());
+ Long userId = post.getUser_id();
+ Users user = userRepository.findById(userId).orElse(null);
+
+ if (user != null) {
+ postData.put("username", user.getUsername());
+ postData.put("avatar_url", user.getAvatarUrl());
+ } else {
+ postData.put("username", null);
+ postData.put("avatar_url", null);
+ }
+
+ postData.put("postContent", post.getPostContent());
+ postData.put("imageUrl", post.getImageUrl());
+ postData.put("postTime", post.getPostTime());
+ postData.put("postLikeNum", post.getPostLikeNum());
+ postData.put("postCollectNum", post.getPostCollectNum());
+ postData.put("title", post.getTitle());
+
+ return postData;
+ } else {
+ throw new RuntimeException("Post not found with id: " + postId);
+ }
+ }
+
+
+ //收藏
+ public void collectPost(Long postId, Long userId) {
+ Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
+ post.setPostCollectNum(post.getPostCollectNum() + 1);
+ postRepository.save(post);
+
+ // 添加到收藏表
+ Collections collection = new Collections();
+ collection.setUserId(userId);
+ collection.setPostNo(postId);
+ collectionsRepository.save(collection);
+ }
+
+ //取消收藏
+ public void uncollectPost(Long postId, Long userId) {
+ Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
+ // 减少帖子收藏数
+ if (post.getPostCollectNum() > 0) {
+ post.setPostCollectNum(post.getPostCollectNum() - 1);
+ postRepository.save(post);
+ }
+
+ // 从收藏表中删除对应记录
+ collectionsRepository.deleteLikeByUserIdAndPostNo(userId, postId);
+ }
+
+ // 获取用户收藏的所有帖子
+ public List<Map<String, Object>> getAllCollections(Long userId) {
+ // 获取用户收藏的帖子ID
+ List<Collections> collections = collectionsRepository.findByUserId(userId);
+
+ // 如果没有收藏的帖子,返回空列表
+ if (collections.isEmpty()) {
+ return new ArrayList<>();
+ }
+
+ List<Map<String, Object>> response = new ArrayList<>();
+ for (Collections collection : collections) {
+ // 根据 postNo 查询帖子
+ Optional<Post> postOptional = postRepository.findById(collection.getPostNo());
+ if (postOptional.isPresent()) {
+ Post post = postOptional.get();
+
+ // 获取帖子作者的信息
+ Optional<Users> userOptional = userRepository.findById(post.getUser_id());
+ if (userOptional.isPresent()) {
+ Users user = userOptional.get();
+
+ // 将帖子数据和用户信息封装到 Map 中
+ Map<String, Object> postInfo = new LinkedHashMap<>();
+ postInfo.put("postNo", post.getPostNo());
+ postInfo.put("title", post.getTitle());
+ postInfo.put("postContent", post.getPostContent());
+ postInfo.put("imageUrl", post.getImageUrl());
+ postInfo.put("userId", post.getUser_id());
+ postInfo.put("username", user.getUsername()); // 帖子作者用户名
+ postInfo.put("avatarUrl", user.getAvatarUrl()); // 帖子作者头像
+
+ response.add(postInfo);
+ }
+ }
+ }
+ return response;
+ }
+
+
+}