mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-24 07:00:49 +08:00
Compare commits
18 Commits
codex/crea
...
feature/da
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8657a06f52 | ||
|
|
09900b34aa | ||
|
|
4e1c3f5839 | ||
|
|
d97cc7df5e | ||
|
|
151242f3ba | ||
|
|
b2783a0168 | ||
|
|
c79bcac217 | ||
|
|
9a06da3bc1 | ||
|
|
98bbc36453 | ||
|
|
4a04f4ec17 | ||
|
|
77be2bfebb | ||
|
|
cf4ca89e19 | ||
|
|
094fc78d92 | ||
|
|
da3d2a6a71 | ||
|
|
15cba0c96e | ||
|
|
98a79acad9 | ||
|
|
4947978f81 | ||
|
|
24cc479a56 |
@@ -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("https://openisle-1307107697.cos.accelerate.myqcloud.com/dynamic_assert/32647273e2334d14adfd4a6ce9db0643.jpeg");
|
||||||
|
conversationRepository.save(chat);
|
||||||
|
|
||||||
|
MessageConversation tech = new MessageConversation();
|
||||||
|
tech.setChannel(true);
|
||||||
|
tech.setName("技术讨论群");
|
||||||
|
tech.setDescription("讨论技术相关话题");
|
||||||
|
tech.setAvatar("https://openisle-1307107697.cos.accelerate.myqcloud.com/dynamic_assert/5edde9a5864e471caa32491dbcdaa8b2.png");
|
||||||
|
conversationRepository.save(tech);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -121,6 +121,7 @@ public class SecurityConfig {
|
|||||||
.requestMatchers(HttpMethod.GET, "/api/reaction-types").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/reaction-types").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/activities/**").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/activities/**").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/sitemap.xml").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/sitemap.xml").permitAll()
|
||||||
|
.requestMatchers(HttpMethod.GET, "/api/channels").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/rss").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/rss").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/point-goods").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/point-goods").permitAll()
|
||||||
.requestMatchers(HttpMethod.POST, "/api/point-goods").permitAll()
|
.requestMatchers(HttpMethod.POST, "/api/point-goods").permitAll()
|
||||||
@@ -156,7 +157,7 @@ public class SecurityConfig {
|
|||||||
uri.startsWith("/api/search") || uri.startsWith("/api/users") ||
|
uri.startsWith("/api/search") || uri.startsWith("/api/users") ||
|
||||||
uri.startsWith("/api/reaction-types") || uri.startsWith("/api/config") ||
|
uri.startsWith("/api/reaction-types") || uri.startsWith("/api/config") ||
|
||||||
uri.startsWith("/api/activities") || uri.startsWith("/api/push/public-key") ||
|
uri.startsWith("/api/activities") || uri.startsWith("/api/push/public-key") ||
|
||||||
uri.startsWith("/api/point-goods") ||
|
uri.startsWith("/api/point-goods") || uri.startsWith("/api/channels") ||
|
||||||
uri.startsWith("/api/sitemap.xml") || uri.startsWith("/api/medals") ||
|
uri.startsWith("/api/sitemap.xml") || uri.startsWith("/api/medals") ||
|
||||||
uri.startsWith("/api/rss"));
|
uri.startsWith("/api/rss"));
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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 com.openisle.service.MessageService;
|
||||||
|
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 MessageService messageService;
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/unread-count")
|
||||||
|
public long unreadCount(Authentication auth) {
|
||||||
|
return messageService.getUnreadChannelCount(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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
17
backend/src/main/java/com/openisle/dto/ChannelDto.java
Normal file
17
backend/src/main/java/com/openisle/dto/ChannelDto.java
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
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 MessageDto lastMessage;
|
||||||
|
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;
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
package com.openisle.repository;
|
package com.openisle.repository;
|
||||||
|
|
||||||
import com.openisle.model.MessageConversation;
|
import com.openisle.model.MessageConversation;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
import org.springframework.stereotype.Repository;
|
|
||||||
|
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
import java.util.List;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
import com.openisle.model.User;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface MessageConversationRepository extends JpaRepository<MessageConversation, Long> {
|
public interface MessageConversationRepository extends JpaRepository<MessageConversation, Long> {
|
||||||
@Query("SELECT c FROM MessageConversation c JOIN c.participants p1 JOIN c.participants p2 WHERE p1.user = :user1 AND p2.user = :user2")
|
@Query("SELECT c FROM MessageConversation c " +
|
||||||
Optional<MessageConversation> findConversationByUsers(@Param("user1") User user1, @Param("user2") User user2);
|
"WHERE c.channel = false AND size(c.participants) = 2 " +
|
||||||
|
"AND EXISTS (SELECT 1 FROM c.participants p1 WHERE p1.user = :user1) " +
|
||||||
|
"AND EXISTS (SELECT 1 FROM c.participants p2 WHERE p2.user = :user2) " +
|
||||||
|
"ORDER BY c.createdAt DESC")
|
||||||
|
List<MessageConversation> findConversationsByUsers(@Param("user1") User user1, @Param("user2") User user2);
|
||||||
|
|
||||||
@Query("SELECT DISTINCT c FROM MessageConversation c " +
|
@Query("SELECT DISTINCT c FROM MessageConversation c " +
|
||||||
"JOIN c.participants p " +
|
"JOIN c.participants p " +
|
||||||
@@ -28,4 +27,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,98 @@
|
|||||||
|
package com.openisle.service;
|
||||||
|
|
||||||
|
import com.openisle.dto.ChannelDto;
|
||||||
|
import com.openisle.dto.MessageDto;
|
||||||
|
import com.openisle.dto.UserSummaryDto;
|
||||||
|
import com.openisle.model.Message;
|
||||||
|
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());
|
||||||
|
if (channel.getLastMessage() != null) {
|
||||||
|
dto.setLastMessage(toMessageDto(channel.getLastMessage()));
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
private MessageDto toMessageDto(Message message) {
|
||||||
|
MessageDto dto = new MessageDto();
|
||||||
|
dto.setId(message.getId());
|
||||||
|
dto.setContent(message.getContent());
|
||||||
|
dto.setConversationId(message.getConversation().getId());
|
||||||
|
dto.setCreatedAt(message.getCreatedAt());
|
||||||
|
|
||||||
|
UserSummaryDto userDto = new UserSummaryDto();
|
||||||
|
userDto.setId(message.getSender().getId());
|
||||||
|
userDto.setUsername(message.getSender().getUsername());
|
||||||
|
userDto.setAvatar(message.getSender().getAvatar());
|
||||||
|
dto.setSender(userDto);
|
||||||
|
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,6 +82,52 @@ 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);
|
||||||
|
|
||||||
|
long channelUnread = getUnreadChannelCount(participant.getUser().getId());
|
||||||
|
messagingTemplate.convertAndSendToUser(username, "/queue/channel-unread", channelUnread);
|
||||||
|
}
|
||||||
|
|
||||||
|
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());
|
||||||
@@ -108,7 +154,8 @@ public class MessageService {
|
|||||||
|
|
||||||
private MessageConversation findOrCreateConversation(User user1, User user2) {
|
private MessageConversation findOrCreateConversation(User user1, User user2) {
|
||||||
log.info("Searching for existing conversation between {} and {}", user1.getUsername(), user2.getUsername());
|
log.info("Searching for existing conversation between {} and {}", user1.getUsername(), user2.getUsername());
|
||||||
return conversationRepository.findConversationByUsers(user1, user2)
|
return conversationRepository.findConversationsByUsers(user1, user2).stream()
|
||||||
|
.findFirst()
|
||||||
.orElseGet(() -> {
|
.orElseGet(() -> {
|
||||||
log.info("No existing conversation found. Creating a new one.");
|
log.info("No existing conversation found. Creating a new one.");
|
||||||
MessageConversation conversation = new MessageConversation();
|
MessageConversation conversation = new MessageConversation();
|
||||||
@@ -134,12 +181,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 +242,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);
|
||||||
|
|
||||||
@@ -208,10 +264,26 @@ public class MessageService {
|
|||||||
List<MessageParticipant> participations = participantRepository.findByUserId(userId);
|
List<MessageParticipant> participations = participantRepository.findByUserId(userId);
|
||||||
long totalUnreadCount = 0;
|
long totalUnreadCount = 0;
|
||||||
for (MessageParticipant p : participations) {
|
for (MessageParticipant p : participations) {
|
||||||
|
if (p.getConversation().isChannel()) continue;
|
||||||
LocalDateTime lastRead = p.getLastReadAt() == null ? LocalDateTime.of(1970, 1, 1, 0, 0) : p.getLastReadAt();
|
LocalDateTime lastRead = p.getLastReadAt() == null ? LocalDateTime.of(1970, 1, 1, 0, 0) : p.getLastReadAt();
|
||||||
// 只计算别人发送给当前用户的未读消息
|
// 只计算别人发送给当前用户的未读消息
|
||||||
totalUnreadCount += messageRepository.countByConversationIdAndCreatedAtAfterAndSenderIdNot(p.getConversation().getId(), lastRead, userId);
|
totalUnreadCount += messageRepository.countByConversationIdAndCreatedAtAfterAndSenderIdNot(p.getConversation().getId(), lastRead, userId);
|
||||||
}
|
}
|
||||||
return totalUnreadCount;
|
return totalUnreadCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public long getUnreadChannelCount(Long userId) {
|
||||||
|
List<MessageParticipant> participations = participantRepository.findByUserId(userId);
|
||||||
|
long unreadChannelCount = 0;
|
||||||
|
for (MessageParticipant p : participations) {
|
||||||
|
if (!p.getConversation().isChannel()) continue;
|
||||||
|
LocalDateTime lastRead = p.getLastReadAt() == null ? LocalDateTime.of(1970, 1, 1, 0, 0) : p.getLastReadAt();
|
||||||
|
long unread = messageRepository.countByConversationIdAndCreatedAtAfterAndSenderIdNot(p.getConversation().getId(), lastRead, userId);
|
||||||
|
if (unread > 0) {
|
||||||
|
unreadChannelCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return unreadChannelCount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,10 @@
|
|||||||
<button class="menu-btn" ref="menuBtn" @click="$emit('toggle-menu')">
|
<button class="menu-btn" ref="menuBtn" @click="$emit('toggle-menu')">
|
||||||
<i class="fas fa-bars"></i>
|
<i class="fas fa-bars"></i>
|
||||||
</button>
|
</button>
|
||||||
<span v-if="isMobile && unreadMessageCount > 0" class="menu-unread-dot"></span>
|
<span
|
||||||
|
v-if="isMobile && (unreadMessageCount > 0 || hasChannelUnread)"
|
||||||
|
class="menu-unread-dot"
|
||||||
|
></span>
|
||||||
</div>
|
</div>
|
||||||
<NuxtLink class="logo-container" :to="`/`" @click="refrechData">
|
<NuxtLink class="logo-container" :to="`/`" @click="refrechData">
|
||||||
<img
|
<img
|
||||||
@@ -53,6 +56,7 @@
|
|||||||
<span v-if="unreadMessageCount > 0" class="unread-badge">{{
|
<span v-if="unreadMessageCount > 0" class="unread-badge">{{
|
||||||
unreadMessageCount
|
unreadMessageCount
|
||||||
}}</span>
|
}}</span>
|
||||||
|
<span v-else-if="hasChannelUnread" class="unread-dot"></span>
|
||||||
</div>
|
</div>
|
||||||
</ToolTip>
|
</ToolTip>
|
||||||
|
|
||||||
@@ -85,6 +89,7 @@ import ToolTip from '~/components/ToolTip.vue'
|
|||||||
import SearchDropdown from '~/components/SearchDropdown.vue'
|
import SearchDropdown from '~/components/SearchDropdown.vue'
|
||||||
import { authState, clearToken, loadCurrentUser } from '~/utils/auth'
|
import { authState, clearToken, loadCurrentUser } from '~/utils/auth'
|
||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
|
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
|
||||||
import { useIsMobile } from '~/utils/screen'
|
import { useIsMobile } from '~/utils/screen'
|
||||||
import { themeState, cycleTheme, ThemeMode } from '~/utils/theme'
|
import { themeState, cycleTheme, ThemeMode } from '~/utils/theme'
|
||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
@@ -103,6 +108,7 @@ const props = defineProps({
|
|||||||
const isLogin = computed(() => authState.loggedIn)
|
const isLogin = computed(() => authState.loggedIn)
|
||||||
const isMobile = useIsMobile()
|
const isMobile = useIsMobile()
|
||||||
const { count: unreadMessageCount, fetchUnreadCount } = useUnreadCount()
|
const { count: unreadMessageCount, fetchUnreadCount } = useUnreadCount()
|
||||||
|
const { hasUnread: hasChannelUnread, fetchChannelUnread } = useChannelsUnreadCount()
|
||||||
const avatar = ref('')
|
const avatar = ref('')
|
||||||
const showSearch = ref(false)
|
const showSearch = ref(false)
|
||||||
const searchDropdown = ref(null)
|
const searchDropdown = ref(null)
|
||||||
@@ -227,8 +233,10 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
const updateUnread = async () => {
|
const updateUnread = async () => {
|
||||||
if (authState.loggedIn) {
|
if (authState.loggedIn) {
|
||||||
// Initialize the unread count composable
|
|
||||||
fetchUnreadCount()
|
fetchUnreadCount()
|
||||||
|
fetchChannelUnread()
|
||||||
|
} else {
|
||||||
|
fetchChannelUnread()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,6 +421,16 @@ onMounted(async () => {
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.unread-dot {
|
||||||
|
position: absolute;
|
||||||
|
top: -2px;
|
||||||
|
right: -4px;
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background-color: #ff4d4f;
|
||||||
|
}
|
||||||
|
|
||||||
.rss-icon {
|
.rss-icon {
|
||||||
animation: rss-glow 2s 3;
|
animation: rss-glow 2s 3;
|
||||||
}
|
}
|
||||||
|
|||||||
92
frontend_nuxt/composables/useChannelsUnreadCount.js
Normal file
92
frontend_nuxt/composables/useChannelsUnreadCount.js
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
import { useWebSocket } from './useWebSocket'
|
||||||
|
import { getToken } from '~/utils/auth'
|
||||||
|
|
||||||
|
const count = ref(0)
|
||||||
|
let isInitialized = false
|
||||||
|
let wsSubscription = null
|
||||||
|
|
||||||
|
export function useChannelsUnreadCount() {
|
||||||
|
const config = useRuntimeConfig()
|
||||||
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
|
const { subscribe, isConnected, connect } = useWebSocket()
|
||||||
|
|
||||||
|
const fetchChannelUnread = async () => {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
count.value = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/api/channels/unread-count`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json()
|
||||||
|
count.value = data
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to fetch channel unread count:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialize = () => {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
count.value = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fetchChannelUnread()
|
||||||
|
if (!isConnected.value) {
|
||||||
|
connect(token)
|
||||||
|
}
|
||||||
|
setupWebSocketListener()
|
||||||
|
}
|
||||||
|
|
||||||
|
const setupWebSocketListener = () => {
|
||||||
|
if (!wsSubscription) {
|
||||||
|
watch(
|
||||||
|
isConnected,
|
||||||
|
(newValue) => {
|
||||||
|
if (newValue && !wsSubscription) {
|
||||||
|
wsSubscription = subscribe('/user/queue/channel-unread', (message) => {
|
||||||
|
const unread = parseInt(message.body, 10)
|
||||||
|
if (!isNaN(unread)) {
|
||||||
|
count.value = unread
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const setFromList = (channels) => {
|
||||||
|
count.value = Array.isArray(channels) ? channels.filter((c) => c.unreadCount > 0).length : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasUnread = computed(() => count.value > 0)
|
||||||
|
|
||||||
|
const token = getToken()
|
||||||
|
if (token) {
|
||||||
|
if (!isInitialized) {
|
||||||
|
isInitialized = true
|
||||||
|
initialize()
|
||||||
|
} else {
|
||||||
|
fetchChannelUnread()
|
||||||
|
if (!isConnected.value) {
|
||||||
|
connect(token)
|
||||||
|
}
|
||||||
|
setupWebSocketListener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
count,
|
||||||
|
hasUnread,
|
||||||
|
fetchChannelUnread,
|
||||||
|
initialize,
|
||||||
|
setFromList,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -55,7 +55,10 @@ const subscribe = (destination, callback) => {
|
|||||||
try {
|
try {
|
||||||
const subscription = client.value.subscribe(destination, (message) => {
|
const subscription = client.value.subscribe(destination, (message) => {
|
||||||
try {
|
try {
|
||||||
if (destination.includes('/queue/unread-count')) {
|
if (
|
||||||
|
destination.includes('/queue/unread-count') ||
|
||||||
|
destination.includes('/queue/channel-unread')
|
||||||
|
) {
|
||||||
callback(message)
|
callback(message)
|
||||||
} else {
|
} else {
|
||||||
const parsedMessage = JSON.parse(message.body)
|
const parsedMessage = JSON.parse(message.body)
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
<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">
|
||||||
@@ -20,8 +22,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<BaseTimeline :items="messages">
|
<BaseTimeline :items="messages">
|
||||||
<template #item="{ item }">
|
<template #item="{ item }">
|
||||||
<div class="message-timestamp">
|
<div class="message-header">
|
||||||
{{ TimeManager.format(item.createdAt) }}
|
<div class="user-name">
|
||||||
|
{{ item.sender.username }}
|
||||||
|
</div>
|
||||||
|
<div class="message-timestamp">
|
||||||
|
{{ TimeManager.format(item.createdAt) }}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="message-content">
|
<div class="message-content">
|
||||||
<div class="info-content-text" v-html="renderMarkdown(item.content)"></div>
|
<div class="info-content-text" v-html="renderMarkdown(item.content)"></div>
|
||||||
@@ -62,6 +69,7 @@ import { renderMarkdown } from '~/utils/markdown'
|
|||||||
import MessageEditor from '~/components/MessageEditor.vue'
|
import MessageEditor from '~/components/MessageEditor.vue'
|
||||||
import { useWebSocket } from '~/composables/useWebSocket'
|
import { useWebSocket } from '~/composables/useWebSocket'
|
||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
|
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
|
||||||
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'
|
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||||
@@ -71,6 +79,7 @@ const route = useRoute()
|
|||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
|
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
|
||||||
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
||||||
|
const { fetchChannelUnread: refreshChannelUnread } = useChannelsUnreadCount()
|
||||||
let subscription = null
|
let subscription = null
|
||||||
|
|
||||||
const messages = ref([])
|
const messages = ref([])
|
||||||
@@ -86,11 +95,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)
|
||||||
@@ -136,6 +147,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
|
||||||
@@ -182,27 +195,40 @@ 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()
|
||||||
@@ -234,6 +260,7 @@ async function markConversationAsRead() {
|
|||||||
})
|
})
|
||||||
// After marking as read, refresh the global unread count
|
// After marking as read, refresh the global unread count
|
||||||
refreshGlobalUnreadCount()
|
refreshGlobalUnreadCount()
|
||||||
|
refreshChannelUnread()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to mark conversation as read', e)
|
console.error('Failed to mark conversation as read', e)
|
||||||
}
|
}
|
||||||
@@ -429,10 +456,22 @@ onUnmounted(() => {
|
|||||||
.message-timestamp {
|
.message-timestamp {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
color: var(--text-color-secondary);
|
color: var(--text-color-secondary);
|
||||||
margin-top: 5px;
|
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.message-header {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-name {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-color);
|
||||||
|
}
|
||||||
|
|
||||||
.message-item.sent {
|
.message-item.sent {
|
||||||
align-self: flex-end;
|
align-self: flex-end;
|
||||||
flex-direction: row-reverse;
|
flex-direction: row-reverse;
|
||||||
|
|||||||
@@ -1,55 +1,111 @@
|
|||||||
<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-if="!loading" class="search-container">
|
|
||||||
<SearchPersonDropdown />
|
|
||||||
</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="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">
|
||||||
|
{{ formatTime(ch.lastMessage?.createdAt || ch.createdAt) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="last-message-row">
|
||||||
|
<div class="last-message">
|
||||||
|
{{
|
||||||
|
ch.lastMessage ? stripMarkdownLength(ch.lastMessage.content, 100) : ch.description
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
<div class="member-count">成员 {{ ch.memberCount }}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -64,6 +120,7 @@ import { getToken, fetchCurrentUser } from '~/utils/auth'
|
|||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { useWebSocket } from '~/composables/useWebSocket'
|
import { useWebSocket } from '~/composables/useWebSocket'
|
||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
|
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
|
||||||
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 SearchPersonDropdown from '~/components/SearchPersonDropdown.vue'
|
||||||
@@ -78,8 +135,14 @@ const currentUser = ref(null)
|
|||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
|
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
|
||||||
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
||||||
|
const { fetchChannelUnread: refreshChannelUnread, setFromList: setChannelUnreadFromList } =
|
||||||
|
useChannelsUnreadCount()
|
||||||
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) {
|
||||||
@@ -120,6 +183,52 @@ 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('无法加载频道')
|
||||||
|
const data = await response.json()
|
||||||
|
channels.value = data
|
||||||
|
setChannelUnreadFromList(data)
|
||||||
|
} 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()
|
||||||
@@ -127,6 +236,7 @@ onActivated(async () => {
|
|||||||
if (currentUser.value) {
|
if (currentUser.value) {
|
||||||
await fetchConversations()
|
await fetchConversations()
|
||||||
refreshGlobalUnreadCount() // Refresh global count when entering the list
|
refreshGlobalUnreadCount() // Refresh global count when entering the list
|
||||||
|
refreshChannelUnread()
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (token && !isConnected.value) {
|
if (token && !isConnected.value) {
|
||||||
connect(token)
|
connect(token)
|
||||||
@@ -147,6 +257,9 @@ watch(isConnected, (newValue) => {
|
|||||||
|
|
||||||
subscription = subscribe(destination, (message) => {
|
subscription = subscribe(destination, (message) => {
|
||||||
fetchConversations()
|
fetchConversations()
|
||||||
|
if (activeTab.value === 'channels') {
|
||||||
|
fetchChannels()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -165,8 +278,22 @@ function goToConversation(id) {
|
|||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.messages-container {
|
.messages-container {
|
||||||
margin: 0 auto;
|
}
|
||||||
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 {
|
||||||
@@ -178,6 +305,8 @@ function goToConversation(id) {
|
|||||||
|
|
||||||
.search-container {
|
.search-container {
|
||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
|
margin-left: 20px;
|
||||||
|
margin-right: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.messages-header {
|
.messages-header {
|
||||||
@@ -217,6 +346,8 @@ function goToConversation(id) {
|
|||||||
.conversation-item {
|
.conversation-item {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
margin-left: 20px;
|
||||||
|
margin-right: 20px;
|
||||||
padding: 8px 10px;
|
padding: 8px 10px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background-color 0.2s ease;
|
transition: background-color 0.2s ease;
|
||||||
@@ -256,6 +387,12 @@ function goToConversation(id) {
|
|||||||
color: var(--text-color);
|
color: var(--text-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.member-count {
|
||||||
|
font-size: 12px;
|
||||||
|
color: gray;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.message-time {
|
.message-time {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: gray;
|
color: gray;
|
||||||
@@ -291,10 +428,20 @@ 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 {
|
.conversation-item {
|
||||||
padding: 10px 10px;
|
margin-left: 10px;
|
||||||
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.messages-title {
|
.messages-title {
|
||||||
|
|||||||
Reference in New Issue
Block a user