mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-03-04 02:50:59 +08:00
Compare commits
1 Commits
codex/fix-
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09c019e70b |
@@ -1,6 +1,8 @@
|
|||||||
package com.openisle.config;
|
package com.openisle.config;
|
||||||
|
|
||||||
|
import com.openisle.model.Channel;
|
||||||
import com.openisle.model.MessageConversation;
|
import com.openisle.model.MessageConversation;
|
||||||
|
import com.openisle.repository.ChannelRepository;
|
||||||
import com.openisle.repository.MessageConversationRepository;
|
import com.openisle.repository.MessageConversationRepository;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.boot.CommandLineRunner;
|
import org.springframework.boot.CommandLineRunner;
|
||||||
@@ -9,24 +11,25 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ChannelInitializer implements CommandLineRunner {
|
public class ChannelInitializer implements CommandLineRunner {
|
||||||
|
private final ChannelRepository channelRepository;
|
||||||
private final MessageConversationRepository conversationRepository;
|
private final MessageConversationRepository conversationRepository;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(String... args) {
|
public void run(String... args) {
|
||||||
if (conversationRepository.countByChannelTrue() == 0) {
|
if (channelRepository.count() == 0) {
|
||||||
MessageConversation chat = new MessageConversation();
|
createChannel("吹水群", "闲聊讨论", "/default-avatar.svg");
|
||||||
chat.setChannel(true);
|
createChannel("技术讨论群", "技术交流", "/default-avatar.svg");
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void createChannel(String name, String description, String avatar) {
|
||||||
|
MessageConversation conversation = new MessageConversation();
|
||||||
|
conversation = conversationRepository.save(conversation);
|
||||||
|
Channel channel = new Channel();
|
||||||
|
channel.setName(name);
|
||||||
|
channel.setDescription(description);
|
||||||
|
channel.setAvatar(avatar);
|
||||||
|
channel.setConversation(conversation);
|
||||||
|
channelRepository.save(channel);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,7 +121,6 @@ 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()
|
||||||
@@ -157,7 +156,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/channels") ||
|
uri.startsWith("/api/point-goods") ||
|
||||||
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"));
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +1,82 @@
|
|||||||
package com.openisle.controller;
|
package com.openisle.controller;
|
||||||
|
|
||||||
import com.openisle.dto.ChannelDto;
|
import com.openisle.dto.ChannelDto;
|
||||||
|
import com.openisle.model.Channel;
|
||||||
|
import com.openisle.model.MessageParticipant;
|
||||||
|
import com.openisle.model.MessageConversation;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
|
import com.openisle.repository.ChannelRepository;
|
||||||
|
import com.openisle.repository.MessageParticipantRepository;
|
||||||
import com.openisle.repository.UserRepository;
|
import com.openisle.repository.UserRepository;
|
||||||
import com.openisle.service.ChannelService;
|
import com.openisle.repository.MessageRepository;
|
||||||
import com.openisle.service.MessageService;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/channels")
|
@RequestMapping("/api/channels")
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ChannelController {
|
public class ChannelController {
|
||||||
private final ChannelService channelService;
|
private final ChannelRepository channelRepository;
|
||||||
private final MessageService messageService;
|
private final MessageParticipantRepository participantRepository;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
|
private final MessageRepository messageRepository;
|
||||||
|
|
||||||
private Long getCurrentUserId(Authentication auth) {
|
private Long getCurrentUserId(Authentication auth) {
|
||||||
User user = userRepository.findByUsername(auth.getName())
|
User user = userRepository.findByUsername(auth.getName()).orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||||
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
|
||||||
return user.getId();
|
return user.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<ChannelDto> listChannels(Authentication auth) {
|
public ResponseEntity<List<ChannelDto>> listChannels(Authentication auth) {
|
||||||
return channelService.listChannels(getCurrentUserId(auth));
|
Long userId = auth == null ? null : getCurrentUserId(auth);
|
||||||
|
List<ChannelDto> channels = channelRepository.findAll().stream()
|
||||||
|
.map(c -> toDto(c, userId))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(channels);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{channelId}/join")
|
@PostMapping("/{id}/join")
|
||||||
public ChannelDto joinChannel(@PathVariable Long channelId, Authentication auth) {
|
public ResponseEntity<Void> joinChannel(@PathVariable Long id, Authentication auth) {
|
||||||
return channelService.joinChannel(channelId, getCurrentUserId(auth));
|
Channel channel = channelRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Channel not found"));
|
||||||
|
Long userId = getCurrentUserId(auth);
|
||||||
|
boolean exists = channel.getConversation().getParticipants().stream().anyMatch(p -> p.getUser().getId().equals(userId));
|
||||||
|
if (!exists) {
|
||||||
|
MessageParticipant participant = new MessageParticipant();
|
||||||
|
participant.setConversation(channel.getConversation());
|
||||||
|
participant.setUser(userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("User not found")));
|
||||||
|
participantRepository.save(participant);
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/unread-count")
|
private ChannelDto toDto(Channel channel, Long userId) {
|
||||||
public long unreadCount(Authentication auth) {
|
ChannelDto dto = new ChannelDto();
|
||||||
return messageService.getUnreadChannelCount(getCurrentUserId(auth));
|
dto.setId(channel.getId());
|
||||||
|
dto.setName(channel.getName());
|
||||||
|
dto.setDescription(channel.getDescription());
|
||||||
|
dto.setAvatar(channel.getAvatar());
|
||||||
|
if (channel.getConversation() != null) {
|
||||||
|
MessageConversation conversation = channel.getConversation();
|
||||||
|
dto.setConversationId(conversation.getId());
|
||||||
|
dto.setMemberCount(conversation.getParticipants().size());
|
||||||
|
if (userId != null) {
|
||||||
|
MessageParticipant self = conversation.getParticipants().stream()
|
||||||
|
.filter(p -> p.getUser().getId().equals(userId))
|
||||||
|
.findFirst().orElse(null);
|
||||||
|
if (self != null) {
|
||||||
|
var lastRead = self.getLastReadAt();
|
||||||
|
dto.setUnreadCount(messageRepository
|
||||||
|
.countByConversationIdAndCreatedAtAfterAndSenderIdNot(conversation.getId(),
|
||||||
|
lastRead == null ? java.time.LocalDateTime.of(1970,1,1,0,0) : lastRead,
|
||||||
|
userId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ public class MessageController {
|
|||||||
|
|
||||||
@PostMapping("/conversations/{conversationId}/messages")
|
@PostMapping("/conversations/{conversationId}/messages")
|
||||||
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
||||||
@RequestBody ChannelMessageRequest req,
|
@RequestBody ContentRequest req,
|
||||||
Authentication auth) {
|
Authentication auth) {
|
||||||
Message message = messageService.sendMessageToConversation(getCurrentUserId(auth), conversationId, req.getContent());
|
Message message = messageService.sendMessageToConversation(getCurrentUserId(auth), conversationId, req.getContent());
|
||||||
return ResponseEntity.ok(toDto(message));
|
return ResponseEntity.ok(toDto(message));
|
||||||
@@ -123,7 +123,7 @@ public class MessageController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static class ChannelMessageRequest {
|
static class ContentRequest {
|
||||||
private String content;
|
private String content;
|
||||||
|
|
||||||
public String getContent() {
|
public String getContent() {
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ public class ChannelDto {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
private String avatar;
|
private String avatar;
|
||||||
private MessageDto lastMessage;
|
private Long conversationId;
|
||||||
private long memberCount;
|
private int memberCount;
|
||||||
private boolean joined;
|
|
||||||
private long unreadCount;
|
private long unreadCount;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,7 @@ 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;
|
||||||
|
private ChannelDto channel;
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ package com.openisle.dto;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -10,11 +11,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;
|
||||||
private long unreadCount;
|
private long unreadCount;
|
||||||
|
private ChannelDto channel;
|
||||||
}
|
}
|
||||||
27
backend/src/main/java/com/openisle/model/Channel.java
Normal file
27
backend/src/main/java/com/openisle/model/Channel.java
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package com.openisle.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "channels")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class Channel {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
|
||||||
|
@OneToOne
|
||||||
|
@JoinColumn(name = "conversation_id")
|
||||||
|
private MessageConversation conversation;
|
||||||
|
}
|
||||||
@@ -20,18 +20,6 @@ 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;
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.openisle.repository;
|
||||||
|
|
||||||
|
import com.openisle.model.Channel;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface ChannelRepository extends JpaRepository<Channel, Long> {
|
||||||
|
Optional<Channel> findByConversationId(Long conversationId);
|
||||||
|
}
|
||||||
@@ -1,19 +1,23 @@
|
|||||||
package com.openisle.repository;
|
package com.openisle.repository;
|
||||||
|
|
||||||
import com.openisle.model.MessageConversation;
|
import com.openisle.model.MessageConversation;
|
||||||
import com.openisle.model.User;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
|
||||||
import org.springframework.data.repository.query.Param;
|
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import com.openisle.model.User;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
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 " +
|
@Query("SELECT c FROM MessageConversation c JOIN c.participants p1 JOIN c.participants p2 WHERE p1.user = :user1 AND p2.user = :user2")
|
||||||
"WHERE p1.user = :user1 AND p2.user = :user2 ORDER BY c.createdAt DESC")
|
Optional<MessageConversation> findConversationByUsers(@Param("user1") User user1, @Param("user2") User user2);
|
||||||
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 " +
|
||||||
@@ -24,8 +28,4 @@ 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();
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,6 +8,9 @@ import com.openisle.repository.MessageConversationRepository;
|
|||||||
import com.openisle.repository.MessageParticipantRepository;
|
import com.openisle.repository.MessageParticipantRepository;
|
||||||
import com.openisle.repository.MessageRepository;
|
import com.openisle.repository.MessageRepository;
|
||||||
import com.openisle.repository.UserRepository;
|
import com.openisle.repository.UserRepository;
|
||||||
|
import com.openisle.repository.ChannelRepository;
|
||||||
|
import com.openisle.model.Channel;
|
||||||
|
import com.openisle.dto.ChannelDto;
|
||||||
import com.openisle.dto.ConversationDetailDto;
|
import com.openisle.dto.ConversationDetailDto;
|
||||||
import com.openisle.dto.ConversationDto;
|
import com.openisle.dto.ConversationDto;
|
||||||
import com.openisle.dto.MessageDto;
|
import com.openisle.dto.MessageDto;
|
||||||
@@ -33,6 +36,7 @@ public class MessageService {
|
|||||||
private final MessageConversationRepository conversationRepository;
|
private final MessageConversationRepository conversationRepository;
|
||||||
private final MessageParticipantRepository participantRepository;
|
private final MessageParticipantRepository participantRepository;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
|
private final ChannelRepository channelRepository;
|
||||||
private final SimpMessagingTemplate messagingTemplate;
|
private final SimpMessagingTemplate messagingTemplate;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -89,15 +93,6 @@ public class MessageService {
|
|||||||
MessageConversation conversation = conversationRepository.findById(conversationId)
|
MessageConversation conversation = conversationRepository.findById(conversationId)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Conversation not found"));
|
.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 message = new Message();
|
||||||
message.setConversation(conversation);
|
message.setConversation(conversation);
|
||||||
message.setSender(sender);
|
message.setSender(sender);
|
||||||
@@ -111,19 +106,15 @@ public class MessageService {
|
|||||||
String conversationDestination = "/topic/conversation/" + conversation.getId();
|
String conversationDestination = "/topic/conversation/" + conversation.getId();
|
||||||
messagingTemplate.convertAndSend(conversationDestination, messageDto);
|
messagingTemplate.convertAndSend(conversationDestination, messageDto);
|
||||||
|
|
||||||
// Notify all participants except sender for updates
|
conversation.getParticipants().forEach(p -> {
|
||||||
for (MessageParticipant participant : conversation.getParticipants()) {
|
if (!p.getUser().getId().equals(senderId)) {
|
||||||
if (participant.getUser().getId().equals(senderId)) continue;
|
String userDestination = "/topic/user/" + p.getUser().getId() + "/messages";
|
||||||
String userDestination = "/topic/user/" + participant.getUser().getId() + "/messages";
|
messagingTemplate.convertAndSend(userDestination, messageDto);
|
||||||
messagingTemplate.convertAndSend(userDestination, messageDto);
|
long unreadCount = getUnreadMessageCount(p.getUser().getId());
|
||||||
|
String recipientUsername = p.getUser().getUsername();
|
||||||
long unreadCount = getUnreadMessageCount(participant.getUser().getId());
|
messagingTemplate.convertAndSendToUser(recipientUsername, "/queue/unread-count", unreadCount);
|
||||||
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;
|
return message;
|
||||||
}
|
}
|
||||||
@@ -144,6 +135,19 @@ public class MessageService {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ChannelDto toDto(Channel channel) {
|
||||||
|
ChannelDto dto = new ChannelDto();
|
||||||
|
dto.setId(channel.getId());
|
||||||
|
dto.setName(channel.getName());
|
||||||
|
dto.setDescription(channel.getDescription());
|
||||||
|
dto.setAvatar(channel.getAvatar());
|
||||||
|
if (channel.getConversation() != null) {
|
||||||
|
dto.setConversationId(channel.getConversation().getId());
|
||||||
|
dto.setMemberCount(channel.getConversation().getParticipants().size());
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
public MessageConversation findOrCreateConversation(Long user1Id, Long user2Id) {
|
public MessageConversation findOrCreateConversation(Long user1Id, Long user2Id) {
|
||||||
User user1 = userRepository.findById(user1Id)
|
User user1 = userRepository.findById(user1Id)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("User1 not found"));
|
.orElseThrow(() -> new IllegalArgumentException("User1 not found"));
|
||||||
@@ -154,8 +158,7 @@ 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.findConversationsByUsers(user1, user2).stream()
|
return conversationRepository.findConversationByUsers(user1, user2)
|
||||||
.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();
|
||||||
@@ -181,18 +184,12 @@ 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()
|
return conversations.stream().map(c -> toDto(c, userId)).collect(Collectors.toList());
|
||||||
.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()));
|
||||||
@@ -207,6 +204,9 @@ public class MessageService {
|
|||||||
})
|
})
|
||||||
.collect(Collectors.toList()));
|
.collect(Collectors.toList()));
|
||||||
|
|
||||||
|
channelRepository.findByConversationId(conversation.getId())
|
||||||
|
.ifPresent(channel -> dto.setChannel(toDto(channel)));
|
||||||
|
|
||||||
MessageParticipant self = conversation.getParticipants().stream()
|
MessageParticipant self = conversation.getParticipants().stream()
|
||||||
.filter(p -> p.getUser().getId().equals(userId))
|
.filter(p -> p.getUser().getId().equals(userId))
|
||||||
.findFirst()
|
.findFirst()
|
||||||
@@ -242,11 +242,10 @@ 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);
|
||||||
|
channelRepository.findByConversationId(conversation.getId())
|
||||||
|
.ifPresent(channel -> detailDto.setChannel(toDto(channel)));
|
||||||
|
|
||||||
return detailDto;
|
return detailDto;
|
||||||
}
|
}
|
||||||
@@ -264,26 +263,10 @@ 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -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(228, 228, 228, 0.884);
|
--menu-selected-background-color: rgba(208, 250, 255, 0.659);
|
||||||
--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,12 +41,6 @@ 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;
|
||||||
|
|||||||
@@ -6,10 +6,7 @@
|
|||||||
<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
|
<span v-if="isMobile && unreadMessageCount > 0" class="menu-unread-dot"></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
|
||||||
@@ -56,7 +53,6 @@
|
|||||||
<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>
|
||||||
|
|
||||||
@@ -89,7 +85,6 @@ 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'
|
||||||
@@ -108,7 +103,6 @@ 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)
|
||||||
@@ -233,10 +227,8 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
const updateUnread = async () => {
|
const updateUnread = async () => {
|
||||||
if (authState.loggedIn) {
|
if (authState.loggedIn) {
|
||||||
|
// Initialize the unread count composable
|
||||||
fetchUnreadCount()
|
fetchUnreadCount()
|
||||||
fetchChannelUnread()
|
|
||||||
} else {
|
|
||||||
fetchChannelUnread()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,16 +413,6 @@ 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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,198 +0,0 @@
|
|||||||
<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,92 +0,0 @@
|
|||||||
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,10 +55,7 @@ const subscribe = (destination, callback) => {
|
|||||||
try {
|
try {
|
||||||
const subscription = client.value.subscribe(destination, (message) => {
|
const subscription = client.value.subscribe(destination, (message) => {
|
||||||
try {
|
try {
|
||||||
if (
|
if (destination.includes('/queue/unread-count')) {
|
||||||
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)
|
||||||
|
|||||||
@@ -4,44 +4,28 @@
|
|||||||
<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">
|
<h2 class="participant-name">{{ channel ? channel.name : otherParticipant?.username }}</h2>
|
||||||
{{ 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 v-if="loading" class="loading-container">加载中...</div>
|
||||||
<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">
|
||||||
<div @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
|
<button @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
|
||||||
{{ loadingMore ? '加载中...' : '查看更多消息' }}
|
{{ loadingMore ? '加载中...' : '查看更多消息' }}
|
||||||
</div>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<BaseTimeline :items="messages">
|
<BaseTimeline :items="messages">
|
||||||
<template #item="{ item }">
|
<template #item="{ item }">
|
||||||
<div class="message-header">
|
<div class="message-timestamp">
|
||||||
<div class="user-name">
|
{{ TimeManager.format(item.createdAt) }}
|
||||||
{{ 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>
|
||||||
</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>
|
||||||
|
|
||||||
@@ -69,21 +53,19 @@ 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'
|
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const route = useRoute()
|
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([])
|
||||||
const participants = ref([])
|
const participants = ref([])
|
||||||
|
const channel = ref(null)
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
const sending = ref(false)
|
const sending = ref(false)
|
||||||
const error = ref(null)
|
const error = ref(null)
|
||||||
@@ -95,13 +77,11 @@ 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 (isChannel.value || !currentUser.value || participants.value.length === 0) {
|
if (!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)
|
||||||
@@ -147,8 +127,7 @@ async function fetchMessages(page = 0) {
|
|||||||
|
|
||||||
if (page === 0) {
|
if (page === 0) {
|
||||||
participants.value = conversationData.participants
|
participants.value = conversationData.participants
|
||||||
conversationName.value = conversationData.name
|
channel.value = conversationData.channel
|
||||||
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
|
||||||
@@ -195,40 +174,33 @@ async function loadMoreMessages() {
|
|||||||
|
|
||||||
async function sendMessage(content, clearInput) {
|
async function sendMessage(content, clearInput) {
|
||||||
if (!content.trim()) return
|
if (!content.trim()) return
|
||||||
sending.value = true
|
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
|
sending.value = true
|
||||||
try {
|
try {
|
||||||
let response
|
let url
|
||||||
if (isChannel.value) {
|
let body
|
||||||
response = await fetch(
|
if (channel.value) {
|
||||||
`${API_BASE_URL}/api/messages/conversations/${conversationId}/messages`,
|
url = `${API_BASE_URL}/api/messages/conversations/${conversationId}/messages`
|
||||||
{
|
body = { content: content }
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ content }),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
const recipient = otherParticipant.value
|
const recipient = otherParticipant.value
|
||||||
if (!recipient) {
|
if (!recipient) {
|
||||||
toast.error('无法确定收信人')
|
toast.error('无法确定收信人')
|
||||||
|
sending.value = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
response = await fetch(`${API_BASE_URL}/api/messages`, {
|
url = `${API_BASE_URL}/api/messages`
|
||||||
method: 'POST',
|
body = { recipientId: recipient.id, content: content }
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
recipientId: recipient.id,
|
|
||||||
content: content,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
if (!response.ok) throw new Error('发送失败')
|
if (!response.ok) throw new Error('发送失败')
|
||||||
|
|
||||||
const newMessage = await response.json()
|
const newMessage = await response.json()
|
||||||
@@ -260,7 +232,6 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -419,21 +390,27 @@ 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 {
|
||||||
color: var(--primary-color);
|
background-color: var(--bg-color-soft);
|
||||||
font-size: 12px;
|
border: 1px solid var(--border-color);
|
||||||
|
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 {
|
||||||
text-decoration: underline;
|
background-color: var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.message-item {
|
.message-item {
|
||||||
@@ -456,22 +433,10 @@ 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;
|
||||||
@@ -501,13 +466,7 @@ onUnmounted(() => {
|
|||||||
margin-right: 20px;
|
margin-right: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-container {
|
.loading-container,
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
height: 300px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error-container {
|
.error-container {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 50px;
|
padding: 50px;
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="messages-container">
|
<div class="messages-container">
|
||||||
<div class="tabs">
|
<div class="tabs">
|
||||||
<div :class="['tab', { active: activeTab === 'messages' }]" @click="activeTab = 'messages'">
|
<div
|
||||||
|
class="tab"
|
||||||
|
:class="{ active: activeTab === 'messages' }"
|
||||||
|
@click="activeTab = 'messages'"
|
||||||
|
>
|
||||||
站内信
|
站内信
|
||||||
</div>
|
</div>
|
||||||
<div :class="['tab', { active: activeTab === 'channels' }]" @click="switchToChannels">
|
<div
|
||||||
|
class="tab"
|
||||||
|
:class="{ active: activeTab === 'channels' }"
|
||||||
|
@click="activeTab = 'channels'"
|
||||||
|
>
|
||||||
频道
|
频道
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -18,16 +26,11 @@
|
|||||||
<div class="error-text">{{ error }}</div>
|
<div class="error-text">{{ error }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="!loading" class="search-container">
|
<div v-else-if="conversations.length === 0" class="empty-container">
|
||||||
<SearchPersonDropdown />
|
<div class="empty-text">暂无会话</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>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
v-if="!loading"
|
|
||||||
v-for="convo in conversations"
|
v-for="convo in conversations"
|
||||||
:key="convo.id"
|
:key="convo.id"
|
||||||
class="conversation-item"
|
class="conversation-item"
|
||||||
@@ -67,45 +70,36 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-else>
|
<div v-else>
|
||||||
<div v-if="loadingChannels" class="loading-message">
|
<div v-if="channelsLoading" class="loading-message">
|
||||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||||
</div>
|
</div>
|
||||||
<div v-else>
|
<div v-else-if="channelsError" class="error-container">
|
||||||
<div v-if="channels.length === 0" class="empty-container">
|
<div class="error-text">{{ channelsError }}</div>
|
||||||
<BasePlaceholder text="暂无频道" icon="fas fa-inbox" />
|
</div>
|
||||||
|
<div v-else-if="channels.length === 0" class="empty-container">
|
||||||
|
<div class="empty-text">暂无频道</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="channel in channels"
|
||||||
|
:key="channel.id"
|
||||||
|
class="conversation-item"
|
||||||
|
@click="goToChannel(channel)"
|
||||||
|
>
|
||||||
|
<div class="conversation-avatar" style="position: relative">
|
||||||
|
<img
|
||||||
|
:src="channel.avatar || '/default-avatar.svg'"
|
||||||
|
:alt="channel.name"
|
||||||
|
class="avatar-img"
|
||||||
|
@error="handleAvatarError"
|
||||||
|
/>
|
||||||
|
<span v-if="channel.unreadCount > 0" class="unread-dot"></span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div class="conversation-content">
|
||||||
v-for="ch in channels"
|
<div class="conversation-header">
|
||||||
:key="ch.id"
|
<div class="participant-name">{{ channel.name }}</div>
|
||||||
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>
|
||||||
<div class="conversation-content">
|
<div class="last-message-row">
|
||||||
<div class="conversation-header">
|
<div class="last-message">{{ channel.description }}</div>
|
||||||
<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>
|
||||||
@@ -120,29 +114,24 @@ 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 BasePlaceholder from '~/components/BasePlaceholder.vue'
|
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
|
const activeTab = ref('messages')
|
||||||
const conversations = ref([])
|
const conversations = ref([])
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
const error = ref(null)
|
const error = ref(null)
|
||||||
|
const channels = ref([])
|
||||||
|
const channelsLoading = ref(true)
|
||||||
|
const channelsError = ref(null)
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const currentUser = ref(null)
|
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) {
|
||||||
@@ -158,7 +147,7 @@ async function fetchConversations() {
|
|||||||
throw new Error(`HTTP error! status: ${response.status}`)
|
throw new Error(`HTTP error! status: ${response.status}`)
|
||||||
}
|
}
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
conversations.value = data
|
conversations.value = data.filter((c) => !c.channel)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error.value = '无法加载会话列表。'
|
error.value = '无法加载会话列表。'
|
||||||
} finally {
|
} finally {
|
||||||
@@ -166,6 +155,28 @@ async function fetchConversations() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchChannels() {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
toast.error('请先登录')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/api/channels`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`)
|
||||||
|
}
|
||||||
|
channels.value = await response.json()
|
||||||
|
} catch (e) {
|
||||||
|
channelsError.value = '无法加载频道。'
|
||||||
|
} finally {
|
||||||
|
channelsLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 获取对话中的另一个参与者(非当前用户)
|
// 获取对话中的另一个参与者(非当前用户)
|
||||||
function getOtherParticipant(conversation) {
|
function getOtherParticipant(conversation) {
|
||||||
if (!currentUser.value || !conversation.participants) return null
|
if (!currentUser.value || !conversation.participants) return null
|
||||||
@@ -183,60 +194,14 @@ 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()
|
||||||
|
|
||||||
if (currentUser.value) {
|
if (currentUser.value) {
|
||||||
await fetchConversations()
|
await fetchConversations()
|
||||||
|
await fetchChannels()
|
||||||
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)
|
||||||
@@ -257,9 +222,7 @@ watch(isConnected, (newValue) => {
|
|||||||
|
|
||||||
subscription = subscribe(destination, (message) => {
|
subscription = subscribe(destination, (message) => {
|
||||||
fetchConversations()
|
fetchConversations()
|
||||||
if (activeTab.value === 'channels') {
|
fetchChannels()
|
||||||
fetchChannels()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -274,16 +237,31 @@ onUnmounted(() => {
|
|||||||
function goToConversation(id) {
|
function goToConversation(id) {
|
||||||
router.push(`/message-box/${id}`)
|
router.push(`/message-box/${id}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function goToChannel(channel) {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) {
|
||||||
|
toast.error('请先登录')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await fetch(`${API_BASE_URL}/api/channels/${channel.id}/join`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
router.push(`/message-box/${channel.conversationId}`)
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.messages-container {
|
.messages-container {
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tabs {
|
.tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
border-bottom: 1px solid var(--normal-border-color);
|
border-bottom: 1px solid #e5e7eb;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tab {
|
.tab {
|
||||||
@@ -292,8 +270,8 @@ function goToConversation(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.tab.active {
|
.tab.active {
|
||||||
font-weight: 600;
|
|
||||||
border-bottom: 2px solid var(--primary-color);
|
border-bottom: 2px solid var(--primary-color);
|
||||||
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-message {
|
.loading-message {
|
||||||
@@ -303,12 +281,6 @@ function goToConversation(id) {
|
|||||||
height: 300px;
|
height: 300px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-container {
|
|
||||||
margin-bottom: 24px;
|
|
||||||
margin-left: 20px;
|
|
||||||
margin-right: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.messages-header {
|
.messages-header {
|
||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
}
|
}
|
||||||
@@ -346,8 +318,6 @@ 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;
|
||||||
@@ -387,12 +357,6 @@ 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;
|
||||||
@@ -429,19 +393,19 @@ function goToConversation(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.unread-dot {
|
.unread-dot {
|
||||||
display: inline-block;
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
width: 8px;
|
width: 8px;
|
||||||
height: 8px;
|
height: 8px;
|
||||||
background-color: #f56c6c;
|
background-color: #f56c6c;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
margin-left: 4px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 响应式设计 */
|
/* 响应式设计 */
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.conversation-item {
|
.messages-container {
|
||||||
margin-left: 10px;
|
padding: 10px 10px;
|
||||||
margin-right: 10px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.messages-title {
|
.messages-title {
|
||||||
|
|||||||
@@ -12,27 +12,25 @@
|
|||||||
<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 class="profile-page-header-user-info-buttons">
|
<div
|
||||||
<div
|
v-if="!isMine && !subscribed"
|
||||||
v-if="!isMine && !subscribed"
|
class="profile-page-header-subscribe-button"
|
||||||
class="profile-page-header-subscribe-button"
|
@click="subscribeUser"
|
||||||
@click="subscribeUser"
|
>
|
||||||
>
|
<i class="fas fa-user-plus"></i>
|
||||||
<i class="fas fa-user-plus"></i>
|
关注
|
||||||
关注
|
</div>
|
||||||
</div>
|
<div
|
||||||
<div
|
v-if="!isMine && subscribed"
|
||||||
v-if="!isMine && subscribed"
|
class="profile-page-header-unsubscribe-button"
|
||||||
class="profile-page-header-unsubscribe-button"
|
@click="unsubscribeUser"
|
||||||
@click="unsubscribeUser"
|
>
|
||||||
>
|
<i class="fas fa-user-minus"></i>
|
||||||
<i class="fas fa-user-minus"></i>
|
取消关注
|
||||||
取消关注
|
</div>
|
||||||
</div>
|
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
|
||||||
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
|
<i class="fas fa-paper-plane"></i>
|
||||||
<i class="fas fa-paper-plane"></i>
|
发私信
|
||||||
发私信
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<LevelProgress
|
<LevelProgress
|
||||||
:exp="levelInfo.exp"
|
:exp="levelInfo.exp"
|
||||||
@@ -642,12 +640,6 @@ 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