Merge pull request #699 from nagisa77/feature/daily_bugfix_0823

daily bugfix
This commit is contained in:
Tim
2025-08-23 02:49:36 +08:00
committed by GitHub
20 changed files with 950 additions and 115 deletions

View File

@@ -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);
}
}
}

View File

@@ -121,6 +121,7 @@ public class SecurityConfig {
.requestMatchers(HttpMethod.GET, "/api/reaction-types").permitAll()
.requestMatchers(HttpMethod.GET, "/api/activities/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/sitemap.xml").permitAll()
.requestMatchers(HttpMethod.GET, "/api/channels").permitAll()
.requestMatchers(HttpMethod.GET, "/api/rss").permitAll()
.requestMatchers(HttpMethod.GET, "/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/reaction-types") || uri.startsWith("/api/config") ||
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/rss"));

View File

@@ -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));
}
}

View File

@@ -59,6 +59,14 @@ public class MessageController {
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")
public ResponseEntity<Void> markAsRead(@PathVariable Long conversationId, Authentication auth) {
messageService.markConversationAsRead(conversationId, getCurrentUserId(auth));
@@ -114,4 +122,16 @@ public class MessageController {
this.content = content;
}
}
static class ChannelMessageRequest {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}

View 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;
}

View File

@@ -8,6 +8,9 @@ import java.util.List;
@Data
public class ConversationDetailDto {
private Long id;
private String name;
private boolean channel;
private String avatar;
private List<UserSummaryDto> participants;
private Page<MessageDto> messages;
}

View File

@@ -10,6 +10,9 @@ import java.util.List;
@Setter
public class ConversationDto {
private Long id;
private String name;
private boolean channel;
private String avatar;
private MessageDto lastMessage;
private List<UserSummaryDto> participants;
private LocalDateTime createdAt;

View File

@@ -20,6 +20,18 @@ public class MessageConversation {
@GeneratedValue(strategy = GenerationType.IDENTITY)
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
@Column(nullable = false, updatable = false)
private LocalDateTime createdAt;

View File

@@ -1,23 +1,22 @@
package com.openisle.repository;
import com.openisle.model.MessageConversation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
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.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import com.openisle.model.User;
import java.util.List;
@Repository
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")
Optional<MessageConversation> findConversationByUsers(@Param("user1") User user1, @Param("user2") User user2);
@Query("SELECT c FROM MessageConversation c " +
"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 " +
"JOIN c.participants p " +
@@ -28,4 +27,8 @@ public interface MessageConversationRepository extends JpaRepository<MessageConv
"WHERE p.user.id = :userId " +
"ORDER BY COALESCE(lm.createdAt, c.createdAt) DESC")
List<MessageConversation> findConversationsByUserIdOrderByLastMessageDesc(@Param("userId") Long userId);
}
List<MessageConversation> findByChannelTrue();
long countByChannelTrue();
}

View File

@@ -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;
}
}

View File

@@ -82,6 +82,52 @@ public class MessageService {
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) {
MessageDto dto = new MessageDto();
dto.setId(message.getId());
@@ -108,7 +154,8 @@ public class MessageService {
private MessageConversation findOrCreateConversation(User user1, User user2) {
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(() -> {
log.info("No existing conversation found. Creating a new one.");
MessageConversation conversation = new MessageConversation();
@@ -134,12 +181,18 @@ public class MessageService {
@Transactional(readOnly = true)
public List<ConversationDto> getConversations(Long 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) {
ConversationDto dto = new ConversationDto();
dto.setId(conversation.getId());
dto.setChannel(conversation.isChannel());
dto.setName(conversation.getName());
dto.setAvatar(conversation.getAvatar());
dto.setCreatedAt(conversation.getCreatedAt());
if (conversation.getLastMessage() != null) {
dto.setLastMessage(toDto(conversation.getLastMessage()));
@@ -189,6 +242,9 @@ public class MessageService {
ConversationDetailDto detailDto = new ConversationDetailDto();
detailDto.setId(conversation.getId());
detailDto.setName(conversation.getName());
detailDto.setChannel(conversation.isChannel());
detailDto.setAvatar(conversation.getAvatar());
detailDto.setParticipants(participants);
detailDto.setMessages(messageDtoPage);
@@ -208,10 +264,26 @@ public class MessageService {
List<MessageParticipant> participations = participantRepository.findByUserId(userId);
long totalUnreadCount = 0;
for (MessageParticipant p : participations) {
if (p.getConversation().isChannel()) continue;
LocalDateTime lastRead = p.getLastReadAt() == null ? LocalDateTime.of(1970, 1, 1, 0, 0) : p.getLastReadAt();
// 只计算别人发送给当前用户的未读消息
totalUnreadCount += messageRepository.countByConversationIdAndCreatedAtAfterAndSenderIdNot(p.getConversation().getId(), lastRead, userId);
}
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;
}
}

View File

@@ -18,7 +18,7 @@
--background-color-blur: rgba(255, 255, 255, 0.57);
--menu-border-color: lightgray;
--normal-border-color: lightgray;
--menu-selected-background-color: rgba(208, 250, 255, 0.659);
--menu-selected-background-color: rgba(228, 228, 228, 0.884);
--menu-text-color: black;
--scroller-background-color: rgba(130, 175, 180, 0.5);
/* --normal-background-color: rgb(241, 241, 241); */

View File

@@ -41,6 +41,12 @@ export default {
margin-top: 10px;
}
.timeline-item:hover {
background-color: var(--menu-selected-background-color);
transition: background-color 0.2s;
border-radius: 10px;
}
.timeline-icon {
position: sticky;
top: 0;

View File

@@ -6,7 +6,10 @@
<button class="menu-btn" ref="menuBtn" @click="$emit('toggle-menu')">
<i class="fas fa-bars"></i>
</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>
<NuxtLink class="logo-container" :to="`/`" @click="refrechData">
<img
@@ -53,6 +56,7 @@
<span v-if="unreadMessageCount > 0" class="unread-badge">{{
unreadMessageCount
}}</span>
<span v-else-if="hasChannelUnread" class="unread-dot"></span>
</div>
</ToolTip>
@@ -85,6 +89,7 @@ import ToolTip from '~/components/ToolTip.vue'
import SearchDropdown from '~/components/SearchDropdown.vue'
import { authState, clearToken, loadCurrentUser } from '~/utils/auth'
import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
import { useIsMobile } from '~/utils/screen'
import { themeState, cycleTheme, ThemeMode } from '~/utils/theme'
import { toast } from '~/main'
@@ -103,6 +108,7 @@ const props = defineProps({
const isLogin = computed(() => authState.loggedIn)
const isMobile = useIsMobile()
const { count: unreadMessageCount, fetchUnreadCount } = useUnreadCount()
const { hasUnread: hasChannelUnread, fetchChannelUnread } = useChannelsUnreadCount()
const avatar = ref('')
const showSearch = ref(false)
const searchDropdown = ref(null)
@@ -227,8 +233,10 @@ onMounted(async () => {
}
const updateUnread = async () => {
if (authState.loggedIn) {
// Initialize the unread count composable
fetchUnreadCount()
fetchChannelUnread()
} else {
fetchChannelUnread()
}
}
@@ -413,6 +421,16 @@ onMounted(async () => {
box-sizing: border-box;
}
.unread-dot {
position: absolute;
top: -2px;
right: -4px;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #ff4d4f;
}
.rss-icon {
animation: rss-glow 2s 3;
}

View File

@@ -0,0 +1,198 @@
<template>
<div class="search-dropdown">
<Dropdown
ref="dropdown"
v-model="selected"
:fetch-options="fetchResults"
remote
menu-class="search-menu"
option-class="search-option"
:show-search="isMobile"
@update:search="keyword = $event"
@close="onClose"
>
<template #display="{ setSearch }">
<div class="search-input">
<i class="search-input-icon fas fa-search"></i>
<input
class="text-input"
v-model="keyword"
placeholder="Search users"
@input="setSearch(keyword)"
/>
</div>
</template>
<template #option="{ option }">
<div class="search-option-item">
<img
:src="option.avatar || '/default-avatar.svg'"
class="avatar"
@error="handleAvatarError"
/>
<div class="result-body">
<div class="result-main" v-html="highlight(option.username)"></div>
<div
v-if="option.introduction"
class="result-sub"
v-html="highlight(option.introduction)"
></div>
</div>
</div>
</template>
</Dropdown>
</div>
</template>
<script setup>
import { ref, watch } from 'vue'
import Dropdown from '~/components/Dropdown.vue'
import { stripMarkdown } from '~/utils/markdown'
import { useIsMobile } from '~/utils/screen'
import { getToken } from '~/utils/auth'
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const emit = defineEmits(['close'])
const keyword = ref('')
const selected = ref(null)
const results = ref([])
const dropdown = ref(null)
const isMobile = useIsMobile()
const toggle = () => {
dropdown.value.toggle()
}
const onClose = () => emit('close')
const fetchResults = async (kw) => {
if (!kw) return []
const res = await fetch(`${API_BASE_URL}/api/search/users?keyword=${encodeURIComponent(kw)}`)
if (!res.ok) return []
const data = await res.json()
results.value = data.map((u) => ({
id: u.id,
username: u.username,
avatar: u.avatar,
introduction: u.introduction,
}))
return results.value
}
const highlight = (text) => {
text = stripMarkdown(text || '')
if (!keyword.value) return text
const reg = new RegExp(keyword.value, 'gi')
return text.replace(reg, (m) => `<span class="highlight">${m}</span>`)
}
const handleAvatarError = (e) => {
e.target.src = '/default-avatar.svg'
}
watch(selected, async (val) => {
if (!val) return
const user = results.value.find((u) => u.id === val)
if (!user) return
const token = getToken()
if (!token) {
navigateTo('/login', { replace: true })
} else {
try {
const res = await fetch(`${API_BASE_URL}/api/messages/conversations`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ recipientId: user.id }),
})
if (res.ok) {
const data = await res.json()
navigateTo(`/message-box/${data.conversationId}`, { replace: true })
}
} catch (e) {
// ignore
}
}
selected.value = null
keyword.value = ''
})
defineExpose({
toggle,
})
</script>
<style scoped>
.search-dropdown {
margin-top: 20px;
width: 500px;
}
.search-input {
padding: 10px;
display: flex;
align-items: center;
width: 100%;
}
.text-input {
background-color: var(--app-menu-background-color);
color: var(--text-color);
border: none;
outline: none;
width: 100%;
margin-left: 10px;
font-size: 16px;
}
.search-menu {
width: 100%;
max-width: 600px;
}
@media (max-width: 768px) {
.search-dropdown {
width: 100%;
}
}
.search-option-item {
display: flex;
gap: 10px;
}
.search-option {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 20px;
}
:deep(.highlight) {
color: var(--primary-color);
}
.avatar {
width: 32px;
height: 32px;
border-radius: 50%;
object-fit: cover;
}
.result-body {
display: flex;
flex-direction: column;
}
.result-main {
font-weight: bold;
}
.result-sub {
font-size: 12px;
color: #666;
}
</style>

View 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,
}
}

View File

@@ -55,7 +55,10 @@ const subscribe = (destination, callback) => {
try {
const subscription = client.value.subscribe(destination, (message) => {
try {
if (destination.includes('/queue/unread-count')) {
if (
destination.includes('/queue/unread-count') ||
destination.includes('/queue/channel-unread')
) {
callback(message)
} else {
const parsedMessage = JSON.parse(message.body)

View File

@@ -1,31 +1,47 @@
<template>
<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">
<i class="fas fa-arrow-left"></i>
</NuxtLink>
<h2 class="participant-name">{{ otherParticipant.username }}</h2>
<h2 class="participant-name">
{{ isChannel ? conversationName : otherParticipant?.username }}
</h2>
</div>
<div class="messages-list" ref="messagesListEl">
<div v-if="loading" class="loading-container">加载中...</div>
<div v-if="loading" class="loading-container">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
</div>
<div v-else-if="error" class="error-container">{{ error }}</div>
<template v-else>
<div class="load-more-container" v-if="hasMoreMessages">
<button @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
<div @click="loadMoreMessages" :disabled="loadingMore" class="load-more-button">
{{ loadingMore ? '加载中...' : '查看更多消息' }}
</button>
</div>
</div>
<BaseTimeline :items="messages">
<template #item="{ item }">
<div class="message-timestamp">
{{ TimeManager.format(item.createdAt) }}
<div class="message-header">
<div class="user-name">
{{ item.sender.username }}
</div>
<div class="message-timestamp">
{{ TimeManager.format(item.createdAt) }}
</div>
</div>
<div class="message-content">
<div class="info-content-text" v-html="renderMarkdown(item.content)"></div>
</div>
</template>
</BaseTimeline>
<div class="empty-container">
<BasePlaceholder
v-if="messages.length === 0"
text="暂无会话,发送消息试试 🎉"
icon="fas fa-inbox"
/>
</div>
</template>
</div>
@@ -53,14 +69,17 @@ import { renderMarkdown } from '~/utils/markdown'
import MessageEditor from '~/components/MessageEditor.vue'
import { useWebSocket } from '~/composables/useWebSocket'
import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
import TimeManager from '~/utils/time'
import BaseTimeline from '~/components/BaseTimeline.vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue'
const config = useRuntimeConfig()
const route = useRoute()
const API_BASE_URL = config.public.apiBaseUrl
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
const { fetchChannelUnread: refreshChannelUnread } = useChannelsUnreadCount()
let subscription = null
const messages = ref([])
@@ -76,11 +95,13 @@ const currentPage = ref(0)
const totalPages = ref(0)
const loadingMore = ref(false)
let scrollInterval = null
const conversationName = ref('')
const isChannel = ref(false)
const hasMoreMessages = computed(() => currentPage.value < totalPages.value - 1)
const otherParticipant = computed(() => {
if (!currentUser.value || participants.value.length === 0) {
if (isChannel.value || !currentUser.value || participants.value.length === 0) {
return null
}
return participants.value.find((p) => p.id !== currentUser.value.id)
@@ -126,6 +147,8 @@ async function fetchMessages(page = 0) {
if (page === 0) {
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
@@ -172,27 +195,40 @@ async function loadMoreMessages() {
async function sendMessage(content, clearInput) {
if (!content.trim()) return
const recipient = otherParticipant.value
if (!recipient) {
toast.error('无法确定收信人')
return
}
sending.value = true
const token = getToken()
try {
const 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,
}),
})
let response
if (isChannel.value) {
response = await fetch(
`${API_BASE_URL}/api/messages/conversations/${conversationId}/messages`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
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('发送失败')
const newMessage = await response.json()
@@ -224,6 +260,7 @@ async function markConversationAsRead() {
})
// After marking as read, refresh the global unread count
refreshGlobalUnreadCount()
refreshChannelUnread()
} catch (e) {
console.error('Failed to mark conversation as read', e)
}
@@ -382,27 +419,21 @@ onUnmounted(() => {
padding-bottom: 100px;
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 10px;
}
.load-more-container {
text-align: center;
margin-bottom: 20px;
}
.load-more-button {
background-color: var(--bg-color-soft);
border: 1px solid var(--border-color);
color: var(--text-color-primary);
padding: 8px 16px;
border-radius: 20px;
color: var(--primary-color);
font-size: 12px;
cursor: pointer;
transition: background-color 0.2s;
}
.load-more-button:hover {
background-color: var(--border-color);
text-decoration: underline;
}
.message-item {
@@ -425,10 +456,22 @@ onUnmounted(() => {
.message-timestamp {
font-size: 11px;
color: var(--text-color-secondary);
margin-top: 5px;
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 {
align-self: flex-end;
flex-direction: row-reverse;
@@ -458,7 +501,13 @@ onUnmounted(() => {
margin-right: 20px;
}
.loading-container,
.loading-container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
.error-container {
text-align: center;
padding: 50px;

View File

@@ -1,50 +1,111 @@
<template>
<div class="messages-container">
<div v-if="loading" class="loading-message">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
<div class="tabs">
<div :class="['tab', { active: activeTab === 'messages' }]" @click="activeTab = 'messages'">
站内信
</div>
<div :class="['tab', { active: activeTab === 'channels' }]" @click="switchToChannels">
频道
</div>
</div>
<div v-else-if="error" class="error-container">
<div class="error-text">{{ error }}</div>
</div>
<div v-else-if="conversations.length === 0" class="empty-container">
<div class="empty-text">暂无会话</div>
</div>
<div
v-for="convo in conversations"
:key="convo.id"
class="conversation-item"
@click="goToConversation(convo.id)"
>
<div class="conversation-avatar">
<img
:src="getOtherParticipant(convo)?.avatar || '/default-avatar.svg'"
:alt="getOtherParticipant(convo)?.username || '用户'"
class="avatar-img"
@error="handleAvatarError"
/>
<div v-if="activeTab === 'messages'">
<div v-if="loading" class="loading-message">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
</div>
<div class="conversation-content">
<div class="conversation-header">
<div class="participant-name">
{{ getOtherParticipant(convo)?.username || '未知用户' }}
</div>
<div class="message-time">
{{ formatTime(convo.lastMessage?.createdAt || convo.createdAt) }}
</div>
<div v-else-if="error" class="error-container">
<div class="error-text">{{ error }}</div>
</div>
<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 class="last-message-row">
<div class="last-message">
{{
convo.lastMessage ? stripMarkdownLength(convo.lastMessage.content, 100) : '暂无消息'
}}
<div class="conversation-content">
<div class="conversation-header">
<div class="participant-name">
{{ getOtherParticipant(convo)?.username || '未知用户' }}
</div>
<div class="message-time">
{{ formatTime(convo.lastMessage?.createdAt || convo.createdAt) }}
</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>
@@ -59,8 +120,11 @@ import { getToken, fetchCurrentUser } from '~/utils/auth'
import { toast } from '~/main'
import { useWebSocket } from '~/composables/useWebSocket'
import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
import TimeManager from '~/utils/time'
import { stripMarkdownLength } from '~/utils/markdown'
import SearchPersonDropdown from '~/components/SearchPersonDropdown.vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue'
const config = useRuntimeConfig()
const conversations = ref([])
@@ -71,8 +135,14 @@ const currentUser = ref(null)
const API_BASE_URL = config.public.apiBaseUrl
const { connect, disconnect, subscribe, isConnected } = useWebSocket()
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
const { fetchChannelUnread: refreshChannelUnread, setFromList: setChannelUnreadFromList } =
useChannelsUnreadCount()
let subscription = null
const activeTab = ref('messages')
const channels = ref([])
const loadingChannels = ref(false)
async function fetchConversations() {
const token = getToken()
if (!token) {
@@ -113,6 +183,52 @@ function handleAvatarError(event) {
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 () => {
loading.value = true
currentUser.value = await fetchCurrentUser()
@@ -120,6 +236,7 @@ onActivated(async () => {
if (currentUser.value) {
await fetchConversations()
refreshGlobalUnreadCount() // Refresh global count when entering the list
refreshChannelUnread()
const token = getToken()
if (token && !isConnected.value) {
connect(token)
@@ -140,6 +257,9 @@ watch(isConnected, (newValue) => {
subscription = subscribe(destination, (message) => {
fetchConversations()
if (activeTab.value === 'channels') {
fetchChannels()
}
})
}
})
@@ -158,8 +278,22 @@ function goToConversation(id) {
<style scoped>
.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 {
@@ -169,6 +303,12 @@ function goToConversation(id) {
height: 300px;
}
.search-container {
margin-bottom: 24px;
margin-left: 20px;
margin-right: 20px;
}
.messages-header {
margin-bottom: 24px;
}
@@ -206,6 +346,8 @@ function goToConversation(id) {
.conversation-item {
display: flex;
align-items: center;
margin-left: 20px;
margin-right: 20px;
padding: 8px 10px;
cursor: pointer;
transition: background-color 0.2s ease;
@@ -245,6 +387,12 @@ function goToConversation(id) {
color: var(--text-color);
}
.member-count {
font-size: 12px;
color: gray;
flex-shrink: 0;
}
.message-time {
font-size: 12px;
color: gray;
@@ -280,10 +428,20 @@ function goToConversation(id) {
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) {
.messages-container {
padding: 10px 10px;
.conversation-item {
margin-left: 10px;
margin-right: 10px;
}
.messages-title {

View File

@@ -12,25 +12,27 @@
<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-description">{{ user.introduction }}</div>
<div
v-if="!isMine && !subscribed"
class="profile-page-header-subscribe-button"
@click="subscribeUser"
>
<i class="fas fa-user-plus"></i>
关注
</div>
<div
v-if="!isMine && subscribed"
class="profile-page-header-unsubscribe-button"
@click="unsubscribeUser"
>
<i class="fas fa-user-minus"></i>
取消关注
</div>
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
<i class="fas fa-paper-plane"></i>
发私信
<div class="profile-page-header-user-info-buttons">
<div
v-if="!isMine && !subscribed"
class="profile-page-header-subscribe-button"
@click="subscribeUser"
>
<i class="fas fa-user-plus"></i>
关注
</div>
<div
v-if="!isMine && subscribed"
class="profile-page-header-unsubscribe-button"
@click="unsubscribeUser"
>
<i class="fas fa-user-minus"></i>
取消关注
</div>
<div v-if="!isMine" class="profile-page-header-subscribe-button" @click="sendMessage">
<i class="fas fa-paper-plane"></i>
发私信
</div>
</div>
<LevelProgress
:exp="levelInfo.exp"
@@ -640,6 +642,12 @@ watch(selectedTab, async (val) => {
color: #666;
}
.profile-page-header-user-info-buttons {
display: flex;
flex-direction: row;
gap: 10px;
}
.profile-page-header-subscribe-button {
display: flex;
flex-direction: row;