package com.timeline.user.controller; import com.timeline.common.response.ResponseEntity; import com.timeline.common.utils.UserContextUtils; import com.timeline.user.ws.WsNotifyService; import lombok.extern.slf4j.Slf4j; import com.timeline.user.dto.NotificationPayload; import com.timeline.user.dto.NotificationType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * WebSocket 测试控制器,用于测试消息推送功能 */ @Slf4j @RestController @RequestMapping("/user/ws-test") public class WebSocketTestController { @Autowired private WsNotifyService wsNotifyService; /** * 测试推送通知消息给当前用户 */ @PostMapping("/notify/self") public ResponseEntity testNotifySelf(@RequestBody Map message) { String userId = UserContextUtils.getCurrentUserId(); if (userId == null || userId.isEmpty()) { return ResponseEntity.error(401, "未获取到用户身份"); } log.info("测试推送通知给用户: {}", userId); NotificationPayload payload = new NotificationPayload(); payload.setContent((String) message.getOrDefault("content", "Test Message")); payload.setCreateTime(java.time.LocalDateTime.now()); String typeStr = (String) message.getOrDefault("type", "SYSTEM_MESSAGE"); try { payload.setType(NotificationType.valueOf(typeStr)); } catch (IllegalArgumentException e) { payload.setType(NotificationType.SYSTEM_MESSAGE); } wsNotifyService.sendNotificationToUser(userId, payload); return ResponseEntity.success("通知已推送给用户: " + userId); } /** * 测试推送通知消息给指定用户 */ @PostMapping("/notify/{targetUserId}") public ResponseEntity testNotifyUser( @PathVariable String targetUserId, @RequestBody Map message) { log.info("测试推送通知给用户: {}", targetUserId); NotificationPayload payload = new NotificationPayload(); payload.setContent((String) message.getOrDefault("content", "Test Message")); payload.setCreateTime(java.time.LocalDateTime.now()); String typeStr = (String) message.getOrDefault("type", "SYSTEM_MESSAGE"); try { payload.setType(NotificationType.valueOf(typeStr)); } catch (IllegalArgumentException e) { payload.setType(NotificationType.SYSTEM_MESSAGE); } wsNotifyService.sendNotificationToUser(targetUserId, payload); return ResponseEntity.success("通知已推送"); } /** * 测试推送好友通知 */ @PostMapping("/friend/{targetUserId}") public ResponseEntity testFriendNotify( @PathVariable String targetUserId, @RequestBody Map message) { log.info("测试推送好友通知给用户: {}", targetUserId); wsNotifyService.sendFriendNotifyToAllChannels(targetUserId, message); return ResponseEntity.success("好友通知已推送"); } /** * 测试推送聊天消息 */ @PostMapping("/chat/{targetUserId}") public ResponseEntity testChatMessage( @PathVariable String targetUserId, @RequestBody Map message) { log.info("测试推送聊天消息给用户: {}", targetUserId); wsNotifyService.sendChatMessage(targetUserId, message); return ResponseEntity.success("聊天消息已推送"); } }