mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-03-02 10:00:54 +08:00
Compare commits
25 Commits
feature/da
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4947978f81 | ||
|
|
24cc479a56 | ||
|
|
8ee1347b17 | ||
|
|
7e95120341 | ||
|
|
2f261983ac | ||
|
|
e8e7b9a245 | ||
|
|
d2bd949ac8 | ||
|
|
605654ec99 | ||
|
|
88127fcf34 | ||
|
|
0a82f0036b | ||
|
|
3a979277e4 | ||
|
|
1c582fbbf1 | ||
|
|
92452da19a | ||
|
|
a2ccaae7aa | ||
|
|
23371d4433 | ||
|
|
e05d65cf49 | ||
|
|
aaf9b35a45 | ||
|
|
61c0336a78 | ||
|
|
69c913394f | ||
|
|
0ed9ad2f2a | ||
|
|
67e912381b | ||
|
|
a6a1c72a37 | ||
|
|
d77baa8a93 | ||
|
|
fce4832407 | ||
|
|
91c8cc9607 |
@@ -0,0 +1,32 @@
|
|||||||
|
package com.openisle.config;
|
||||||
|
|
||||||
|
import com.openisle.model.MessageConversation;
|
||||||
|
import com.openisle.repository.MessageConversationRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChannelInitializer implements CommandLineRunner {
|
||||||
|
private final MessageConversationRepository conversationRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(String... args) {
|
||||||
|
if (conversationRepository.countByChannelTrue() == 0) {
|
||||||
|
MessageConversation chat = new MessageConversation();
|
||||||
|
chat.setChannel(true);
|
||||||
|
chat.setName("吹水群");
|
||||||
|
chat.setDescription("吹水聊天");
|
||||||
|
chat.setAvatar("/default-avatar.svg");
|
||||||
|
conversationRepository.save(chat);
|
||||||
|
|
||||||
|
MessageConversation tech = new MessageConversation();
|
||||||
|
tech.setChannel(true);
|
||||||
|
tech.setName("技术讨论群");
|
||||||
|
tech.setDescription("讨论技术相关话题");
|
||||||
|
tech.setAvatar("/default-avatar.svg");
|
||||||
|
conversationRepository.save(tech);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,19 +92,20 @@ public class SecurityConfig {
|
|||||||
cfg.setAllowedHeaders(List.of("*"));
|
cfg.setAllowedHeaders(List.of("*"));
|
||||||
cfg.setAllowCredentials(true);
|
cfg.setAllowCredentials(true);
|
||||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
source.registerCorsConfiguration("/**", cfg);
|
source.registerCorsConfiguration("/api/**", cfg);
|
||||||
return source;
|
return source;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.csrf(csrf -> csrf.disable())
|
http.csrf(csrf -> csrf.disable())
|
||||||
.cors(Customizer.withDefaults()) // 让 Spring 自带 CorsFilter 处理预检
|
.cors(Customizer.withDefaults())
|
||||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
.headers(h -> h.frameOptions(f -> f.sameOrigin()))
|
||||||
|
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.exceptionHandling(eh -> eh.accessDeniedHandler(customAccessDeniedHandler))
|
.exceptionHandling(eh -> eh.accessDeniedHandler(customAccessDeniedHandler))
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||||
.requestMatchers("/ws/**").permitAll()
|
.requestMatchers("/api/ws/**", "/api/sockjs/**").permitAll()
|
||||||
.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
|
.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/comments/**").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/comments/**").permitAll()
|
||||||
@@ -173,7 +174,8 @@ public class SecurityConfig {
|
|||||||
response.getWriter().write("{\"error\": \"Invalid or expired token\"}");
|
response.getWriter().write("{\"error\": \"Invalid or expired token\"}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else if (!uri.startsWith("/api/auth") && !publicGet && !uri.startsWith("/ws")) {
|
} else if (!uri.startsWith("/api/auth") && !publicGet
|
||||||
|
&& !uri.startsWith("/api/ws") && !uri.startsWith("/api/sockjs")) {
|
||||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
response.setContentType("application/json");
|
response.setContentType("application/json");
|
||||||
response.getWriter().write("{\"error\": \"Missing token\"}");
|
response.getWriter().write("{\"error\": \"Missing token\"}");
|
||||||
|
|||||||
@@ -41,28 +41,38 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||||
// Registers the "/ws" endpoint, enabling SockJS fallback options so that alternate transports may be used if WebSocket is not available.
|
// 1) 原生 WebSocket(不带 SockJS)
|
||||||
registry.addEndpoint("/ws")
|
registry.addEndpoint("/api/ws")
|
||||||
// 安全改进:使用具体的允许源,而不是通配符
|
.setAllowedOriginPatterns(
|
||||||
.setAllowedOrigins(
|
"https://staging.open-isle.com",
|
||||||
"http://127.0.0.1:8080",
|
"https://www.staging.open-isle.com",
|
||||||
"http://127.0.0.1:3000",
|
websiteUrl,
|
||||||
"http://127.0.0.1:3001",
|
websiteUrl.replace("://www.", "://"),
|
||||||
"http://127.0.0.1",
|
"http://localhost:*",
|
||||||
"http://localhost:8080",
|
"http://127.0.0.1:*",
|
||||||
"http://localhost:3000",
|
"http://192.168.7.98:*",
|
||||||
"http://localhost:3001",
|
"http://30.211.97.238:*"
|
||||||
"http://localhost",
|
);
|
||||||
"http://30.211.97.238:3000",
|
|
||||||
"http://30.211.97.238",
|
// 2) SockJS 回退:单独路径
|
||||||
"http://192.168.7.98",
|
registry.addEndpoint("/api/sockjs")
|
||||||
"http://192.168.7.98:3000",
|
.setAllowedOriginPatterns(
|
||||||
websiteUrl,
|
"https://staging.open-isle.com",
|
||||||
websiteUrl.replace("://www.", "://")
|
"https://www.staging.open-isle.com",
|
||||||
|
websiteUrl,
|
||||||
|
websiteUrl.replace("://www.", "://"),
|
||||||
|
"http://localhost:*",
|
||||||
|
"http://127.0.0.1:*",
|
||||||
|
"http://192.168.7.98:*",
|
||||||
|
"http://30.211.97.238:*"
|
||||||
)
|
)
|
||||||
.withSockJS();
|
.withSockJS()
|
||||||
|
.setWebSocketEnabled(true)
|
||||||
|
.setSessionCookieNeeded(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void configureClientInboundChannel(ChannelRegistration registration) {
|
public void configureClientInboundChannel(ChannelRegistration registration) {
|
||||||
registration.interceptors(new ChannelInterceptor() {
|
registration.interceptors(new ChannelInterceptor() {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.openisle.controller;
|
||||||
|
|
||||||
|
import com.openisle.dto.ChannelDto;
|
||||||
|
import com.openisle.model.User;
|
||||||
|
import com.openisle.repository.UserRepository;
|
||||||
|
import com.openisle.service.ChannelService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/channels")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChannelController {
|
||||||
|
private final ChannelService channelService;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
private Long getCurrentUserId(Authentication auth) {
|
||||||
|
User user = userRepository.findByUsername(auth.getName())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||||
|
return user.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<ChannelDto> listChannels(Authentication auth) {
|
||||||
|
return channelService.listChannels(getCurrentUserId(auth));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{channelId}/join")
|
||||||
|
public ChannelDto joinChannel(@PathVariable Long channelId, Authentication auth) {
|
||||||
|
return channelService.joinChannel(channelId, getCurrentUserId(auth));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,6 +59,14 @@ public class MessageController {
|
|||||||
return ResponseEntity.ok(toDto(message));
|
return ResponseEntity.ok(toDto(message));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/conversations/{conversationId}/messages")
|
||||||
|
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
||||||
|
@RequestBody ChannelMessageRequest req,
|
||||||
|
Authentication auth) {
|
||||||
|
Message message = messageService.sendMessageToConversation(getCurrentUserId(auth), conversationId, req.getContent());
|
||||||
|
return ResponseEntity.ok(toDto(message));
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/conversations/{conversationId}/read")
|
@PostMapping("/conversations/{conversationId}/read")
|
||||||
public ResponseEntity<Void> markAsRead(@PathVariable Long conversationId, Authentication auth) {
|
public ResponseEntity<Void> markAsRead(@PathVariable Long conversationId, Authentication auth) {
|
||||||
messageService.markConversationAsRead(conversationId, getCurrentUserId(auth));
|
messageService.markConversationAsRead(conversationId, getCurrentUserId(auth));
|
||||||
@@ -114,4 +122,16 @@ public class MessageController {
|
|||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static class ChannelMessageRequest {
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
public String getContent() {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContent(String content) {
|
||||||
|
this.content = content;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
16
backend/src/main/java/com/openisle/dto/ChannelDto.java
Normal file
16
backend/src/main/java/com/openisle/dto/ChannelDto.java
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package com.openisle.dto;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class ChannelDto {
|
||||||
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
private String description;
|
||||||
|
private String avatar;
|
||||||
|
private long memberCount;
|
||||||
|
private boolean joined;
|
||||||
|
private long unreadCount;
|
||||||
|
}
|
||||||
@@ -8,6 +8,9 @@ import java.util.List;
|
|||||||
@Data
|
@Data
|
||||||
public class ConversationDetailDto {
|
public class ConversationDetailDto {
|
||||||
private Long id;
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
private boolean channel;
|
||||||
|
private String avatar;
|
||||||
private List<UserSummaryDto> participants;
|
private List<UserSummaryDto> participants;
|
||||||
private Page<MessageDto> messages;
|
private Page<MessageDto> messages;
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,9 @@ import java.util.List;
|
|||||||
@Setter
|
@Setter
|
||||||
public class ConversationDto {
|
public class ConversationDto {
|
||||||
private Long id;
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
private boolean channel;
|
||||||
|
private String avatar;
|
||||||
private MessageDto lastMessage;
|
private MessageDto lastMessage;
|
||||||
private List<UserSummaryDto> participants;
|
private List<UserSummaryDto> participants;
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|||||||
@@ -20,6 +20,18 @@ public class MessageConversation {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
|
// Indicates whether this conversation represents a public channel
|
||||||
|
@Column(nullable = false)
|
||||||
|
private boolean channel = false;
|
||||||
|
|
||||||
|
// Channel metadata
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(columnDefinition = "TEXT")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
|
||||||
@CreationTimestamp
|
@CreationTimestamp
|
||||||
@Column(nullable = false, updatable = false)
|
@Column(nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|||||||
@@ -28,4 +28,8 @@ public interface MessageConversationRepository extends JpaRepository<MessageConv
|
|||||||
"WHERE p.user.id = :userId " +
|
"WHERE p.user.id = :userId " +
|
||||||
"ORDER BY COALESCE(lm.createdAt, c.createdAt) DESC")
|
"ORDER BY COALESCE(lm.createdAt, c.createdAt) DESC")
|
||||||
List<MessageConversation> findConversationsByUserIdOrderByLastMessageDesc(@Param("userId") Long userId);
|
List<MessageConversation> findConversationsByUserIdOrderByLastMessageDesc(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
List<MessageConversation> findByChannelTrue();
|
||||||
|
|
||||||
|
long countByChannelTrue();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.openisle.service;
|
||||||
|
|
||||||
|
import com.openisle.dto.ChannelDto;
|
||||||
|
import com.openisle.model.MessageConversation;
|
||||||
|
import com.openisle.model.MessageParticipant;
|
||||||
|
import com.openisle.model.User;
|
||||||
|
import com.openisle.repository.MessageConversationRepository;
|
||||||
|
import com.openisle.repository.MessageParticipantRepository;
|
||||||
|
import com.openisle.repository.MessageRepository;
|
||||||
|
import com.openisle.repository.UserRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChannelService {
|
||||||
|
private final MessageConversationRepository conversationRepository;
|
||||||
|
private final MessageParticipantRepository participantRepository;
|
||||||
|
private final MessageRepository messageRepository;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<ChannelDto> listChannels(Long userId) {
|
||||||
|
List<MessageConversation> channels = conversationRepository.findByChannelTrue();
|
||||||
|
return channels.stream().map(c -> toDto(c, userId)).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public ChannelDto joinChannel(Long channelId, Long userId) {
|
||||||
|
MessageConversation channel = conversationRepository.findById(channelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Channel not found"));
|
||||||
|
User user = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||||
|
participantRepository.findByConversationIdAndUserId(channelId, userId)
|
||||||
|
.orElseGet(() -> {
|
||||||
|
MessageParticipant p = new MessageParticipant();
|
||||||
|
p.setConversation(channel);
|
||||||
|
p.setUser(user);
|
||||||
|
MessageParticipant saved = participantRepository.save(p);
|
||||||
|
channel.getParticipants().add(saved);
|
||||||
|
return saved;
|
||||||
|
});
|
||||||
|
return toDto(channel, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ChannelDto toDto(MessageConversation channel, Long userId) {
|
||||||
|
ChannelDto dto = new ChannelDto();
|
||||||
|
dto.setId(channel.getId());
|
||||||
|
dto.setName(channel.getName());
|
||||||
|
dto.setDescription(channel.getDescription());
|
||||||
|
dto.setAvatar(channel.getAvatar());
|
||||||
|
dto.setMemberCount(channel.getParticipants().size());
|
||||||
|
boolean joined = channel.getParticipants().stream()
|
||||||
|
.anyMatch(p -> p.getUser().getId().equals(userId));
|
||||||
|
dto.setJoined(joined);
|
||||||
|
if (joined) {
|
||||||
|
MessageParticipant participant = channel.getParticipants().stream()
|
||||||
|
.filter(p -> p.getUser().getId().equals(userId))
|
||||||
|
.findFirst().orElse(null);
|
||||||
|
LocalDateTime lastRead = participant.getLastReadAt() == null
|
||||||
|
? LocalDateTime.of(1970, 1, 1, 0, 0)
|
||||||
|
: participant.getLastReadAt();
|
||||||
|
long unread = messageRepository
|
||||||
|
.countByConversationIdAndCreatedAtAfterAndSenderIdNot(channel.getId(), lastRead, userId);
|
||||||
|
dto.setUnreadCount(unread);
|
||||||
|
} else {
|
||||||
|
dto.setUnreadCount(0);
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,6 +82,49 @@ public class MessageService {
|
|||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Message sendMessageToConversation(Long senderId, Long conversationId, String content) {
|
||||||
|
User sender = userRepository.findById(senderId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Sender not found"));
|
||||||
|
MessageConversation conversation = conversationRepository.findById(conversationId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Conversation not found"));
|
||||||
|
|
||||||
|
// Join the conversation if not already a participant (useful for channels)
|
||||||
|
participantRepository.findByConversationIdAndUserId(conversationId, senderId)
|
||||||
|
.orElseGet(() -> {
|
||||||
|
MessageParticipant p = new MessageParticipant();
|
||||||
|
p.setConversation(conversation);
|
||||||
|
p.setUser(sender);
|
||||||
|
return participantRepository.save(p);
|
||||||
|
});
|
||||||
|
|
||||||
|
Message message = new Message();
|
||||||
|
message.setConversation(conversation);
|
||||||
|
message.setSender(sender);
|
||||||
|
message.setContent(content);
|
||||||
|
message = messageRepository.save(message);
|
||||||
|
|
||||||
|
conversation.setLastMessage(message);
|
||||||
|
conversationRepository.save(conversation);
|
||||||
|
|
||||||
|
MessageDto messageDto = toDto(message);
|
||||||
|
String conversationDestination = "/topic/conversation/" + conversation.getId();
|
||||||
|
messagingTemplate.convertAndSend(conversationDestination, messageDto);
|
||||||
|
|
||||||
|
// Notify all participants except sender for updates
|
||||||
|
for (MessageParticipant participant : conversation.getParticipants()) {
|
||||||
|
if (participant.getUser().getId().equals(senderId)) continue;
|
||||||
|
String userDestination = "/topic/user/" + participant.getUser().getId() + "/messages";
|
||||||
|
messagingTemplate.convertAndSend(userDestination, messageDto);
|
||||||
|
|
||||||
|
long unreadCount = getUnreadMessageCount(participant.getUser().getId());
|
||||||
|
String username = participant.getUser().getUsername();
|
||||||
|
messagingTemplate.convertAndSendToUser(username, "/queue/unread-count", unreadCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
private MessageDto toDto(Message message) {
|
private MessageDto toDto(Message message) {
|
||||||
MessageDto dto = new MessageDto();
|
MessageDto dto = new MessageDto();
|
||||||
dto.setId(message.getId());
|
dto.setId(message.getId());
|
||||||
@@ -134,12 +177,18 @@ public class MessageService {
|
|||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public List<ConversationDto> getConversations(Long userId) {
|
public List<ConversationDto> getConversations(Long userId) {
|
||||||
List<MessageConversation> conversations = conversationRepository.findConversationsByUserIdOrderByLastMessageDesc(userId);
|
List<MessageConversation> conversations = conversationRepository.findConversationsByUserIdOrderByLastMessageDesc(userId);
|
||||||
return conversations.stream().map(c -> toDto(c, userId)).collect(Collectors.toList());
|
return conversations.stream()
|
||||||
|
.filter(c -> !c.isChannel())
|
||||||
|
.map(c -> toDto(c, userId))
|
||||||
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ConversationDto toDto(MessageConversation conversation, Long userId) {
|
private ConversationDto toDto(MessageConversation conversation, Long userId) {
|
||||||
ConversationDto dto = new ConversationDto();
|
ConversationDto dto = new ConversationDto();
|
||||||
dto.setId(conversation.getId());
|
dto.setId(conversation.getId());
|
||||||
|
dto.setChannel(conversation.isChannel());
|
||||||
|
dto.setName(conversation.getName());
|
||||||
|
dto.setAvatar(conversation.getAvatar());
|
||||||
dto.setCreatedAt(conversation.getCreatedAt());
|
dto.setCreatedAt(conversation.getCreatedAt());
|
||||||
if (conversation.getLastMessage() != null) {
|
if (conversation.getLastMessage() != null) {
|
||||||
dto.setLastMessage(toDto(conversation.getLastMessage()));
|
dto.setLastMessage(toDto(conversation.getLastMessage()));
|
||||||
@@ -189,6 +238,9 @@ public class MessageService {
|
|||||||
|
|
||||||
ConversationDetailDto detailDto = new ConversationDetailDto();
|
ConversationDetailDto detailDto = new ConversationDetailDto();
|
||||||
detailDto.setId(conversation.getId());
|
detailDto.setId(conversation.getId());
|
||||||
|
detailDto.setName(conversation.getName());
|
||||||
|
detailDto.setChannel(conversation.isChannel());
|
||||||
|
detailDto.setAvatar(conversation.getAvatar());
|
||||||
detailDto.setParticipants(participants);
|
detailDto.setParticipants(participants);
|
||||||
detailDto.setMessages(messageDtoPage);
|
detailDto.setMessages(messageDtoPage);
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
--background-color-blur: rgba(255, 255, 255, 0.57);
|
--background-color-blur: rgba(255, 255, 255, 0.57);
|
||||||
--menu-border-color: lightgray;
|
--menu-border-color: lightgray;
|
||||||
--normal-border-color: lightgray;
|
--normal-border-color: lightgray;
|
||||||
--menu-selected-background-color: rgba(208, 250, 255, 0.659);
|
--menu-selected-background-color: rgba(228, 228, 228, 0.884);
|
||||||
--menu-text-color: black;
|
--menu-text-color: black;
|
||||||
--scroller-background-color: rgba(130, 175, 180, 0.5);
|
--scroller-background-color: rgba(130, 175, 180, 0.5);
|
||||||
/* --normal-background-color: rgb(241, 241, 241); */
|
/* --normal-background-color: rgb(241, 241, 241); */
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ export default {
|
|||||||
margin-top: 10px;
|
margin-top: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.timeline-item:hover {
|
||||||
|
background-color: var(--menu-selected-background-color);
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
.timeline-icon {
|
.timeline-icon {
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 0;
|
top: 0;
|
||||||
|
|||||||
198
frontend_nuxt/components/SearchPersonDropdown.vue
Normal file
198
frontend_nuxt/components/SearchPersonDropdown.vue
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
<template>
|
||||||
|
<div class="search-dropdown">
|
||||||
|
<Dropdown
|
||||||
|
ref="dropdown"
|
||||||
|
v-model="selected"
|
||||||
|
:fetch-options="fetchResults"
|
||||||
|
remote
|
||||||
|
menu-class="search-menu"
|
||||||
|
option-class="search-option"
|
||||||
|
:show-search="isMobile"
|
||||||
|
@update:search="keyword = $event"
|
||||||
|
@close="onClose"
|
||||||
|
>
|
||||||
|
<template #display="{ setSearch }">
|
||||||
|
<div class="search-input">
|
||||||
|
<i class="search-input-icon fas fa-search"></i>
|
||||||
|
<input
|
||||||
|
class="text-input"
|
||||||
|
v-model="keyword"
|
||||||
|
placeholder="Search users"
|
||||||
|
@input="setSearch(keyword)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #option="{ option }">
|
||||||
|
<div class="search-option-item">
|
||||||
|
<img
|
||||||
|
:src="option.avatar || '/default-avatar.svg'"
|
||||||
|
class="avatar"
|
||||||
|
@error="handleAvatarError"
|
||||||
|
/>
|
||||||
|
<div class="result-body">
|
||||||
|
<div class="result-main" v-html="highlight(option.username)"></div>
|
||||||
|
<div
|
||||||
|
v-if="option.introduction"
|
||||||
|
class="result-sub"
|
||||||
|
v-html="highlight(option.introduction)"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, watch } from 'vue'
|
||||||
|
import Dropdown from '~/components/Dropdown.vue'
|
||||||
|
import { stripMarkdown } from '~/utils/markdown'
|
||||||
|
import { useIsMobile } from '~/utils/screen'
|
||||||
|
import { getToken } from '~/utils/auth'
|
||||||
|
const config = useRuntimeConfig()
|
||||||
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
|
|
||||||
|
const emit = defineEmits(['close'])
|
||||||
|
|
||||||
|
const keyword = ref('')
|
||||||
|
const selected = ref(null)
|
||||||
|
const results = ref([])
|
||||||
|
const dropdown = ref(null)
|
||||||
|
const isMobile = useIsMobile()
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
dropdown.value.toggle()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onClose = () => emit('close')
|
||||||
|
|
||||||
|
const fetchResults = async (kw) => {
|
||||||
|
if (!kw) return []
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/search/users?keyword=${encodeURIComponent(kw)}`)
|
||||||
|
if (!res.ok) return []
|
||||||
|
const data = await res.json()
|
||||||
|
results.value = data.map((u) => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
introduction: u.introduction,
|
||||||
|
}))
|
||||||
|
return results.value
|
||||||
|
}
|
||||||
|
|
||||||
|
const highlight = (text) => {
|
||||||
|
text = stripMarkdown(text || '')
|
||||||
|
if (!keyword.value) return text
|
||||||
|
const reg = new RegExp(keyword.value, 'gi')
|
||||||
|
return text.replace(reg, (m) => `<span class="highlight">${m}</span>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAvatarError = (e) => {
|
||||||
|
e.target.src = '/default-avatar.svg'
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(selected, async (val) => {
|
||||||
|
if (!val) return
|
||||||
|
const user = results.value.find((u) => u.id === val)
|
||||||
|
if (!user) return
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
navigateTo('/login', { replace: true })
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/messages/conversations`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ recipientId: user.id }),
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json()
|
||||||
|
navigateTo(`/message-box/${data.conversationId}`, { replace: true })
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selected.value = null
|
||||||
|
keyword.value = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
toggle,
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-dropdown {
|
||||||
|
margin-top: 20px;
|
||||||
|
width: 500px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input {
|
||||||
|
padding: 10px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-input {
|
||||||
|
background-color: var(--app-menu-background-color);
|
||||||
|
color: var(--text-color);
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
width: 100%;
|
||||||
|
margin-left: 10px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-menu {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.search-dropdown {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-option-item {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-option {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.highlight) {
|
||||||
|
color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 50%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-main {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-sub {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,85 +1,83 @@
|
|||||||
import { ref } from 'vue';
|
import { ref } from 'vue'
|
||||||
import { Client } from '@stomp/stompjs';
|
import { Client } from '@stomp/stompjs'
|
||||||
import SockJS from 'sockjs-client/dist/sockjs.min.js';
|
import SockJS from 'sockjs-client/dist/sockjs.min.js'
|
||||||
import { useRuntimeConfig } from '#app';
|
import { useRuntimeConfig } from '#app'
|
||||||
|
|
||||||
const client = ref(null);
|
const client = ref(null)
|
||||||
const isConnected = ref(false);
|
const isConnected = ref(false)
|
||||||
|
|
||||||
const connect = (token) => {
|
const connect = (token) => {
|
||||||
if (isConnected.value) {
|
if (isConnected.value) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const config = useRuntimeConfig();
|
const config = useRuntimeConfig()
|
||||||
const API_BASE_URL = config.public.apiBaseUrl;
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
const socketUrl = `${API_BASE_URL}/ws`;
|
const socketUrl = `${API_BASE_URL}/api/sockjs`
|
||||||
|
|
||||||
const socket = new SockJS(socketUrl);
|
const socket = new SockJS(socketUrl)
|
||||||
const stompClient = new Client({
|
const stompClient = new Client({
|
||||||
webSocketFactory: () => socket,
|
webSocketFactory: () => socket,
|
||||||
connectHeaders: {
|
connectHeaders: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
debug: function (str) {
|
debug: function (str) {},
|
||||||
},
|
reconnectDelay: 5000,
|
||||||
reconnectDelay: 5000,
|
heartbeatIncoming: 4000,
|
||||||
heartbeatIncoming: 4000,
|
heartbeatOutgoing: 4000,
|
||||||
heartbeatOutgoing: 4000,
|
})
|
||||||
});
|
|
||||||
|
|
||||||
stompClient.onConnect = (frame) => {
|
stompClient.onConnect = (frame) => {
|
||||||
isConnected.value = true;
|
isConnected.value = true
|
||||||
};
|
}
|
||||||
|
|
||||||
stompClient.onStompError = (frame) => {
|
stompClient.onStompError = (frame) => {
|
||||||
console.error('WebSocket STOMP error:', frame);
|
console.error('WebSocket STOMP error:', frame)
|
||||||
};
|
}
|
||||||
|
|
||||||
stompClient.activate();
|
stompClient.activate()
|
||||||
client.value = stompClient;
|
client.value = stompClient
|
||||||
};
|
}
|
||||||
|
|
||||||
const disconnect = () => {
|
const disconnect = () => {
|
||||||
if (client.value) {
|
if (client.value) {
|
||||||
isConnected.value = false;
|
isConnected.value = false
|
||||||
client.value.deactivate();
|
client.value.deactivate()
|
||||||
client.value = null;
|
client.value = null
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
const subscribe = (destination, callback) => {
|
const subscribe = (destination, callback) => {
|
||||||
|
if (!isConnected.value || !client.value || !client.value.connected) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
if (!isConnected.value || !client.value || !client.value.connected) {
|
try {
|
||||||
return null;
|
const subscription = client.value.subscribe(destination, (message) => {
|
||||||
}
|
try {
|
||||||
|
if (destination.includes('/queue/unread-count')) {
|
||||||
|
callback(message)
|
||||||
|
} else {
|
||||||
|
const parsedMessage = JSON.parse(message.body)
|
||||||
|
callback(parsedMessage)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
callback(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
try {
|
return subscription
|
||||||
const subscription = client.value.subscribe(destination, (message) => {
|
} catch (error) {
|
||||||
try {
|
return null
|
||||||
if (destination.includes('/queue/unread-count')) {
|
}
|
||||||
callback(message);
|
}
|
||||||
} else {
|
|
||||||
const parsedMessage = JSON.parse(message.body);
|
|
||||||
callback(parsedMessage);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
callback(message);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return subscription;
|
|
||||||
} catch (error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useWebSocket() {
|
export function useWebSocket() {
|
||||||
return {
|
return {
|
||||||
client,
|
client,
|
||||||
isConnected,
|
isConnected,
|
||||||
connect,
|
connect,
|
||||||
disconnect,
|
disconnect,
|
||||||
subscribe,
|
subscribe,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,24 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="chat-container">
|
<div class="chat-container">
|
||||||
<div v-if="!loading && otherParticipant" class="chat-header">
|
<div v-if="!loading" class="chat-header">
|
||||||
<NuxtLink to="/message-box" class="back-button">
|
<NuxtLink to="/message-box" class="back-button">
|
||||||
<i class="fas fa-arrow-left"></i>
|
<i class="fas fa-arrow-left"></i>
|
||||||
</NuxtLink>
|
</NuxtLink>
|
||||||
<h2 class="participant-name">{{ otherParticipant.username }}</h2>
|
<h2 class="participant-name">
|
||||||
|
{{ isChannel ? conversationName : otherParticipant?.username }}
|
||||||
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="messages-list" ref="messagesListEl">
|
<div class="messages-list" ref="messagesListEl">
|
||||||
<div v-if="loading" class="loading-container">加载中...</div>
|
<div v-if="loading" class="loading-container">
|
||||||
|
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||||
|
</div>
|
||||||
<div v-else-if="error" class="error-container">{{ error }}</div>
|
<div v-else-if="error" class="error-container">{{ error }}</div>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<div class="load-more-container" v-if="hasMoreMessages">
|
<div class="load-more-container" v-if="hasMoreMessages">
|
||||||
<button @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
|
<div @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
|
||||||
{{ loadingMore ? '加载中...' : '查看更多消息' }}
|
{{ loadingMore ? '加载中...' : '查看更多消息' }}
|
||||||
</button>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<BaseTimeline :items="messages">
|
<BaseTimeline :items="messages">
|
||||||
<template #item="{ item }">
|
<template #item="{ item }">
|
||||||
@@ -26,6 +30,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
|
<div class="empty-container">
|
||||||
|
<BasePlaceholder
|
||||||
|
v-if="messages.length === 0"
|
||||||
|
text="暂无会话,发送消息试试 🎉"
|
||||||
|
icon="fas fa-inbox"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -55,6 +66,7 @@ import { useWebSocket } from '~/composables/useWebSocket'
|
|||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
import TimeManager from '~/utils/time'
|
import TimeManager from '~/utils/time'
|
||||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||||
|
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
@@ -76,11 +88,13 @@ const currentPage = ref(0)
|
|||||||
const totalPages = ref(0)
|
const totalPages = ref(0)
|
||||||
const loadingMore = ref(false)
|
const loadingMore = ref(false)
|
||||||
let scrollInterval = null
|
let scrollInterval = null
|
||||||
|
const conversationName = ref('')
|
||||||
|
const isChannel = ref(false)
|
||||||
|
|
||||||
const hasMoreMessages = computed(() => currentPage.value < totalPages.value - 1)
|
const hasMoreMessages = computed(() => currentPage.value < totalPages.value - 1)
|
||||||
|
|
||||||
const otherParticipant = computed(() => {
|
const otherParticipant = computed(() => {
|
||||||
if (!currentUser.value || participants.value.length === 0) {
|
if (isChannel.value || !currentUser.value || participants.value.length === 0) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
return participants.value.find((p) => p.id !== currentUser.value.id)
|
return participants.value.find((p) => p.id !== currentUser.value.id)
|
||||||
@@ -126,6 +140,8 @@ async function fetchMessages(page = 0) {
|
|||||||
|
|
||||||
if (page === 0) {
|
if (page === 0) {
|
||||||
participants.value = conversationData.participants
|
participants.value = conversationData.participants
|
||||||
|
conversationName.value = conversationData.name
|
||||||
|
isChannel.value = conversationData.channel
|
||||||
}
|
}
|
||||||
|
|
||||||
// Since the backend sorts by descending, we need to reverse for correct chat order
|
// Since the backend sorts by descending, we need to reverse for correct chat order
|
||||||
@@ -172,34 +188,51 @@ async function loadMoreMessages() {
|
|||||||
|
|
||||||
async function sendMessage(content, clearInput) {
|
async function sendMessage(content, clearInput) {
|
||||||
if (!content.trim()) return
|
if (!content.trim()) return
|
||||||
|
|
||||||
const recipient = otherParticipant.value
|
|
||||||
if (!recipient) {
|
|
||||||
toast.error('无法确定收信人')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sending.value = true
|
sending.value = true
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE_URL}/api/messages`, {
|
let response
|
||||||
method: 'POST',
|
if (isChannel.value) {
|
||||||
headers: {
|
response = await fetch(
|
||||||
'Content-Type': 'application/json',
|
`${API_BASE_URL}/api/messages/conversations/${conversationId}/messages`,
|
||||||
Authorization: `Bearer ${token}`,
|
{
|
||||||
},
|
method: 'POST',
|
||||||
body: JSON.stringify({
|
headers: {
|
||||||
recipientId: recipient.id,
|
'Content-Type': 'application/json',
|
||||||
content: content,
|
Authorization: `Bearer ${token}`,
|
||||||
}),
|
},
|
||||||
})
|
body: JSON.stringify({ content }),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
const recipient = otherParticipant.value
|
||||||
|
if (!recipient) {
|
||||||
|
toast.error('无法确定收信人')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response = await fetch(`${API_BASE_URL}/api/messages`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
recipientId: recipient.id,
|
||||||
|
content: content,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
if (!response.ok) throw new Error('发送失败')
|
if (!response.ok) throw new Error('发送失败')
|
||||||
|
|
||||||
const newMessage = await response.json()
|
const newMessage = await response.json()
|
||||||
messages.value.push(newMessage)
|
messages.value.push({
|
||||||
|
...newMessage,
|
||||||
|
src: newMessage.sender.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
navigateTo(`/users/${newMessage.sender.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
clearInput()
|
clearInput()
|
||||||
|
|
||||||
// Use a more reliable scroll approach
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
}, 100)
|
}, 100)
|
||||||
@@ -277,7 +310,13 @@ watch(isConnected, (newValue) => {
|
|||||||
subscription = subscribe(`/topic/conversation/${conversationId}`, (message) => {
|
subscription = subscribe(`/topic/conversation/${conversationId}`, (message) => {
|
||||||
// 避免重复显示当前用户发送的消息
|
// 避免重复显示当前用户发送的消息
|
||||||
if (message.sender.id !== currentUser.value.id) {
|
if (message.sender.id !== currentUser.value.id) {
|
||||||
messages.value.push(message)
|
messages.value.push({
|
||||||
|
...message,
|
||||||
|
src: message.sender.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
navigateTo(`/users/${message.sender.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
// 实时收到消息时自动标记为已读
|
// 实时收到消息时自动标记为已读
|
||||||
markConversationAsRead()
|
markConversationAsRead()
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -372,27 +411,21 @@ onUnmounted(() => {
|
|||||||
padding-bottom: 100px;
|
padding-bottom: 100px;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 20px;
|
|
||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.load-more-container {
|
.load-more-container {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.load-more-button {
|
.load-more-button {
|
||||||
background-color: var(--bg-color-soft);
|
color: var(--primary-color);
|
||||||
border: 1px solid var(--border-color);
|
font-size: 12px;
|
||||||
color: var(--text-color-primary);
|
|
||||||
padding: 8px 16px;
|
|
||||||
border-radius: 20px;
|
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background-color 0.2s;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.load-more-button:hover {
|
.load-more-button:hover {
|
||||||
background-color: var(--border-color);
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
.message-item {
|
.message-item {
|
||||||
@@ -445,12 +478,30 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
.message-input-area {
|
.message-input-area {
|
||||||
margin-left: 20px;
|
margin-left: 20px;
|
||||||
|
margin-right: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 300px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-container,
|
|
||||||
.error-container {
|
.error-container {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 50px;
|
padding: 50px;
|
||||||
color: var(--text-color-secondary);
|
color: var(--text-color-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.messages-list {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area {
|
||||||
|
margin-left: 10px;
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,50 +1,104 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="messages-container">
|
<div class="messages-container">
|
||||||
<div v-if="loading" class="loading-message">
|
<div class="tabs">
|
||||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
<div :class="['tab', { active: activeTab === 'messages' }]" @click="activeTab = 'messages'">
|
||||||
|
站内信
|
||||||
|
</div>
|
||||||
|
<div :class="['tab', { active: activeTab === 'channels' }]" @click="switchToChannels">
|
||||||
|
频道
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-else-if="error" class="error-container">
|
<div v-if="activeTab === 'messages'">
|
||||||
<div class="error-text">{{ error }}</div>
|
<div v-if="loading" class="loading-message">
|
||||||
</div>
|
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||||
|
|
||||||
<div v-else-if="conversations.length === 0" class="empty-container">
|
|
||||||
<div class="empty-text">暂无会话</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
v-for="convo in conversations"
|
|
||||||
:key="convo.id"
|
|
||||||
class="conversation-item"
|
|
||||||
@click="goToConversation(convo.id)"
|
|
||||||
>
|
|
||||||
<div class="conversation-avatar">
|
|
||||||
<img
|
|
||||||
:src="getOtherParticipant(convo)?.avatar || '/default-avatar.svg'"
|
|
||||||
:alt="getOtherParticipant(convo)?.username || '用户'"
|
|
||||||
class="avatar-img"
|
|
||||||
@error="handleAvatarError"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="conversation-content">
|
<div v-else-if="error" class="error-container">
|
||||||
<div class="conversation-header">
|
<div class="error-text">{{ error }}</div>
|
||||||
<div class="participant-name">
|
</div>
|
||||||
{{ getOtherParticipant(convo)?.username || '未知用户' }}
|
|
||||||
</div>
|
<div v-if="!loading" class="search-container">
|
||||||
<div class="message-time">
|
<SearchPersonDropdown />
|
||||||
{{ formatTime(convo.lastMessage?.createdAt || convo.createdAt) }}
|
</div>
|
||||||
</div>
|
|
||||||
|
<div v-if="!loading && conversations.length === 0" class="empty-container">
|
||||||
|
<BasePlaceholder v-if="conversations.length === 0" text="暂无会话" icon="fas fa-inbox" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="!loading"
|
||||||
|
v-for="convo in conversations"
|
||||||
|
:key="convo.id"
|
||||||
|
class="conversation-item"
|
||||||
|
@click="goToConversation(convo.id)"
|
||||||
|
>
|
||||||
|
<div class="conversation-avatar">
|
||||||
|
<img
|
||||||
|
:src="getOtherParticipant(convo)?.avatar || '/default-avatar.svg'"
|
||||||
|
:alt="getOtherParticipant(convo)?.username || '用户'"
|
||||||
|
class="avatar-img"
|
||||||
|
@error="handleAvatarError"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="last-message-row">
|
<div class="conversation-content">
|
||||||
<div class="last-message">
|
<div class="conversation-header">
|
||||||
{{
|
<div class="participant-name">
|
||||||
convo.lastMessage ? stripMarkdownLength(convo.lastMessage.content, 100) : '暂无消息'
|
{{ getOtherParticipant(convo)?.username || '未知用户' }}
|
||||||
}}
|
</div>
|
||||||
|
<div class="message-time">
|
||||||
|
{{ formatTime(convo.lastMessage?.createdAt || convo.createdAt) }}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="convo.unreadCount > 0" class="unread-count-badge">
|
|
||||||
{{ convo.unreadCount }}
|
<div class="last-message-row">
|
||||||
|
<div class="last-message">
|
||||||
|
{{
|
||||||
|
convo.lastMessage ? stripMarkdownLength(convo.lastMessage.content, 100) : '暂无消息'
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
<div v-if="convo.unreadCount > 0" class="unread-count-badge">
|
||||||
|
{{ convo.unreadCount }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else>
|
||||||
|
<div v-if="loadingChannels" class="loading-message">
|
||||||
|
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||||
|
</div>
|
||||||
|
<div v-else>
|
||||||
|
<div v-if="channels.length === 0" class="empty-container">
|
||||||
|
<BasePlaceholder text="暂无频道" icon="fas fa-inbox" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="ch in channels"
|
||||||
|
:key="ch.id"
|
||||||
|
class="conversation-item"
|
||||||
|
@click="goToChannel(ch.id)"
|
||||||
|
>
|
||||||
|
<div class="conversation-avatar">
|
||||||
|
<img
|
||||||
|
:src="ch.avatar || '/default-avatar.svg'"
|
||||||
|
:alt="ch.name"
|
||||||
|
class="avatar-img"
|
||||||
|
@error="handleAvatarError"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="conversation-content">
|
||||||
|
<div class="conversation-header">
|
||||||
|
<div class="participant-name">
|
||||||
|
{{ ch.name }}
|
||||||
|
<span v-if="ch.unreadCount > 0" class="unread-dot"></span>
|
||||||
|
</div>
|
||||||
|
<div class="message-time">成员 {{ ch.memberCount }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="last-message-row">
|
||||||
|
<div class="last-message">{{ ch.description }}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -61,6 +115,8 @@ import { useWebSocket } from '~/composables/useWebSocket'
|
|||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
import TimeManager from '~/utils/time'
|
import TimeManager from '~/utils/time'
|
||||||
import { stripMarkdownLength } from '~/utils/markdown'
|
import { stripMarkdownLength } from '~/utils/markdown'
|
||||||
|
import SearchPersonDropdown from '~/components/SearchPersonDropdown.vue'
|
||||||
|
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const conversations = ref([])
|
const conversations = ref([])
|
||||||
@@ -73,6 +129,10 @@ const { connect, disconnect, subscribe, isConnected } = useWebSocket()
|
|||||||
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
||||||
let subscription = null
|
let subscription = null
|
||||||
|
|
||||||
|
const activeTab = ref('messages')
|
||||||
|
const channels = ref([])
|
||||||
|
const loadingChannels = ref(false)
|
||||||
|
|
||||||
async function fetchConversations() {
|
async function fetchConversations() {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (!token) {
|
if (!token) {
|
||||||
@@ -113,6 +173,50 @@ function handleAvatarError(event) {
|
|||||||
event.target.src = '/default-avatar.svg'
|
event.target.src = '/default-avatar.svg'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchChannels() {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
toast.error('请先登录')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loadingChannels.value = true
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/api/channels`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
if (!response.ok) throw new Error('无法加载频道')
|
||||||
|
channels.value = await response.json()
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e.message)
|
||||||
|
} finally {
|
||||||
|
loadingChannels.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchToChannels() {
|
||||||
|
activeTab.value = 'channels'
|
||||||
|
if (channels.value.length === 0) {
|
||||||
|
fetchChannels()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function goToChannel(id) {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
toast.error('请先登录')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await fetch(`${API_BASE_URL}/api/channels/${id}/join`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
router.push(`/message-box/${id}`)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onActivated(async () => {
|
onActivated(async () => {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
currentUser.value = await fetchCurrentUser()
|
currentUser.value = await fetchCurrentUser()
|
||||||
@@ -162,6 +266,22 @@ function goToConversation(id) {
|
|||||||
padding: 20px;
|
padding: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.tabs {
|
||||||
|
display: flex;
|
||||||
|
border-bottom: 1px solid var(--normal-border-color);
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
padding: 8px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab.active {
|
||||||
|
font-weight: 600;
|
||||||
|
border-bottom: 2px solid var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
.loading-message {
|
.loading-message {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -169,6 +289,10 @@ function goToConversation(id) {
|
|||||||
height: 300px;
|
height: 300px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.search-container {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
.messages-header {
|
.messages-header {
|
||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
}
|
}
|
||||||
@@ -280,10 +404,19 @@ function goToConversation(id) {
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.unread-dot {
|
||||||
|
display: inline-block;
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
background-color: #f56c6c;
|
||||||
|
border-radius: 50%;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
/* 响应式设计 */
|
/* 响应式设计 */
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.messages-container {
|
.messages-container {
|
||||||
padding: 16px 12px;
|
padding: 10px 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.messages-title {
|
.messages-title {
|
||||||
@@ -295,7 +428,7 @@ function goToConversation(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.conversation-item {
|
.conversation-item {
|
||||||
padding: 12px 16px;
|
padding: 6px 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.avatar-img {
|
.avatar-img {
|
||||||
@@ -315,34 +448,4 @@ function goToConversation(id) {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 480px) {
|
|
||||||
.messages-container {
|
|
||||||
padding: 12px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversations-list {
|
|
||||||
max-height: 400px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-item {
|
|
||||||
padding: 10px 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.avatar-img {
|
|
||||||
width: 36px;
|
|
||||||
height: 36px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.conversation-avatar {
|
|
||||||
margin-right: 12px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 大屏幕设备 */
|
|
||||||
@media (min-width: 1024px) {
|
|
||||||
.conversations-list {
|
|
||||||
max-height: 700px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -12,25 +12,27 @@
|
|||||||
<div class="profile-page-header-user-info">
|
<div class="profile-page-header-user-info">
|
||||||
<div class="profile-page-header-user-info-name">{{ user.username }}</div>
|
<div class="profile-page-header-user-info-name">{{ user.username }}</div>
|
||||||
<div class="profile-page-header-user-info-description">{{ user.introduction }}</div>
|
<div class="profile-page-header-user-info-description">{{ user.introduction }}</div>
|
||||||
<div
|
<div class="profile-page-header-user-info-buttons">
|
||||||
v-if="!isMine && !subscribed"
|
<div
|
||||||
class="profile-page-header-subscribe-button"
|
v-if="!isMine && !subscribed"
|
||||||
@click="subscribeUser"
|
class="profile-page-header-subscribe-button"
|
||||||
>
|
@click="subscribeUser"
|
||||||
<i class="fas fa-user-plus"></i>
|
>
|
||||||
关注
|
<i class="fas fa-user-plus"></i>
|
||||||
</div>
|
关注
|
||||||
<div
|
</div>
|
||||||
v-if="!isMine && subscribed"
|
<div
|
||||||
class="profile-page-header-unsubscribe-button"
|
v-if="!isMine && subscribed"
|
||||||
@click="unsubscribeUser"
|
class="profile-page-header-unsubscribe-button"
|
||||||
>
|
@click="unsubscribeUser"
|
||||||
<i class="fas fa-user-minus"></i>
|
>
|
||||||
取消关注
|
<i class="fas fa-user-minus"></i>
|
||||||
</div>
|
取消关注
|
||||||
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
|
</div>
|
||||||
<i class="fas fa-paper-plane"></i>
|
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
|
||||||
发私信
|
<i class="fas fa-paper-plane"></i>
|
||||||
|
发私信
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<LevelProgress
|
<LevelProgress
|
||||||
:exp="levelInfo.exp"
|
:exp="levelInfo.exp"
|
||||||
@@ -640,6 +642,12 @@ watch(selectedTab, async (val) => {
|
|||||||
color: #666;
|
color: #666;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profile-page-header-user-info-buttons {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
.profile-page-header-subscribe-button {
|
.profile-page-header-subscribe-button {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
|
|||||||
Reference in New Issue
Block a user