mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-09 08:30:55 +08:00
Compare commits
4 Commits
codex/add-
...
codex/crea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ee1347b17 | ||
|
|
7e95120341 | ||
|
|
2f261983ac | ||
|
|
e8e7b9a245 |
@@ -1,35 +0,0 @@
|
||||
package com.openisle.config;
|
||||
|
||||
import com.openisle.model.Channel;
|
||||
import com.openisle.model.MessageConversation;
|
||||
import com.openisle.repository.ChannelRepository;
|
||||
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 ChannelRepository channelRepository;
|
||||
private final MessageConversationRepository conversationRepository;
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
if (channelRepository.count() == 0) {
|
||||
createChannel("吹水群", "闲聊讨论", "/default-avatar.svg");
|
||||
createChannel("技术讨论群", "技术交流", "/default-avatar.svg");
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
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.repository.ChannelRepository;
|
||||
import com.openisle.repository.MessageParticipantRepository;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.repository.MessageRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/channels")
|
||||
@RequiredArgsConstructor
|
||||
public class ChannelController {
|
||||
private final ChannelRepository channelRepository;
|
||||
private final MessageParticipantRepository participantRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final MessageRepository messageRepository;
|
||||
|
||||
private Long getCurrentUserId(Authentication auth) {
|
||||
User user = userRepository.findByUsername(auth.getName()).orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||
return user.getId();
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<ChannelDto>> listChannels(Authentication 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("/{id}/join")
|
||||
public ResponseEntity<Void> joinChannel(@PathVariable Long id, Authentication 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();
|
||||
}
|
||||
|
||||
private ChannelDto toDto(Channel 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.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;
|
||||
}
|
||||
}
|
||||
@@ -59,14 +59,6 @@ public class MessageController {
|
||||
return ResponseEntity.ok(toDto(message));
|
||||
}
|
||||
|
||||
@PostMapping("/conversations/{conversationId}/messages")
|
||||
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
||||
@RequestBody ContentRequest 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));
|
||||
@@ -122,16 +114,4 @@ public class MessageController {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
|
||||
static class ContentRequest {
|
||||
private String content;
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ChannelDto {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String avatar;
|
||||
private Long conversationId;
|
||||
private int memberCount;
|
||||
private long unreadCount;
|
||||
}
|
||||
@@ -10,5 +10,4 @@ public class ConversationDetailDto {
|
||||
private Long id;
|
||||
private List<UserSummaryDto> participants;
|
||||
private Page<MessageDto> messages;
|
||||
private ChannelDto channel;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.openisle.dto;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -15,5 +14,4 @@ public class ConversationDto {
|
||||
private List<UserSummaryDto> participants;
|
||||
private LocalDateTime createdAt;
|
||||
private long unreadCount;
|
||||
private ChannelDto channel;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -8,9 +8,6 @@ import com.openisle.repository.MessageConversationRepository;
|
||||
import com.openisle.repository.MessageParticipantRepository;
|
||||
import com.openisle.repository.MessageRepository;
|
||||
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.ConversationDto;
|
||||
import com.openisle.dto.MessageDto;
|
||||
@@ -36,7 +33,6 @@ public class MessageService {
|
||||
private final MessageConversationRepository conversationRepository;
|
||||
private final MessageParticipantRepository participantRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final ChannelRepository channelRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
@Transactional
|
||||
@@ -86,39 +82,6 @@ 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"));
|
||||
|
||||
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);
|
||||
|
||||
conversation.getParticipants().forEach(p -> {
|
||||
if (!p.getUser().getId().equals(senderId)) {
|
||||
String userDestination = "/topic/user/" + p.getUser().getId() + "/messages";
|
||||
messagingTemplate.convertAndSend(userDestination, messageDto);
|
||||
long unreadCount = getUnreadMessageCount(p.getUser().getId());
|
||||
String recipientUsername = p.getUser().getUsername();
|
||||
messagingTemplate.convertAndSendToUser(recipientUsername, "/queue/unread-count", unreadCount);
|
||||
}
|
||||
});
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private MessageDto toDto(Message message) {
|
||||
MessageDto dto = new MessageDto();
|
||||
dto.setId(message.getId());
|
||||
@@ -135,19 +98,6 @@ public class MessageService {
|
||||
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) {
|
||||
User user1 = userRepository.findById(user1Id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("User1 not found"));
|
||||
@@ -204,9 +154,6 @@ public class MessageService {
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
channelRepository.findByConversationId(conversation.getId())
|
||||
.ifPresent(channel -> dto.setChannel(toDto(channel)));
|
||||
|
||||
MessageParticipant self = conversation.getParticipants().stream()
|
||||
.filter(p -> p.getUser().getId().equals(userId))
|
||||
.findFirst()
|
||||
@@ -244,8 +191,6 @@ public class MessageService {
|
||||
detailDto.setId(conversation.getId());
|
||||
detailDto.setParticipants(participants);
|
||||
detailDto.setMessages(messageDtoPage);
|
||||
channelRepository.findByConversationId(conversation.getId())
|
||||
.ifPresent(channel -> detailDto.setChannel(toDto(channel)));
|
||||
|
||||
return detailDto;
|
||||
}
|
||||
|
||||
@@ -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); */
|
||||
|
||||
@@ -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;
|
||||
|
||||
198
frontend_nuxt/components/SearchPersonDropdown.vue
Normal file
198
frontend_nuxt/components/SearchPersonDropdown.vue
Normal file
@@ -0,0 +1,198 @@
|
||||
<template>
|
||||
<div class="search-dropdown">
|
||||
<Dropdown
|
||||
ref="dropdown"
|
||||
v-model="selected"
|
||||
:fetch-options="fetchResults"
|
||||
remote
|
||||
menu-class="search-menu"
|
||||
option-class="search-option"
|
||||
:show-search="isMobile"
|
||||
@update:search="keyword = $event"
|
||||
@close="onClose"
|
||||
>
|
||||
<template #display="{ setSearch }">
|
||||
<div class="search-input">
|
||||
<i class="search-input-icon fas fa-search"></i>
|
||||
<input
|
||||
class="text-input"
|
||||
v-model="keyword"
|
||||
placeholder="Search users"
|
||||
@input="setSearch(keyword)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #option="{ option }">
|
||||
<div class="search-option-item">
|
||||
<img
|
||||
:src="option.avatar || '/default-avatar.svg'"
|
||||
class="avatar"
|
||||
@error="handleAvatarError"
|
||||
/>
|
||||
<div class="result-body">
|
||||
<div class="result-main" v-html="highlight(option.username)"></div>
|
||||
<div
|
||||
v-if="option.introduction"
|
||||
class="result-sub"
|
||||
v-html="highlight(option.introduction)"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import Dropdown from '~/components/Dropdown.vue'
|
||||
import { stripMarkdown } from '~/utils/markdown'
|
||||
import { useIsMobile } from '~/utils/screen'
|
||||
import { getToken } from '~/utils/auth'
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
|
||||
const keyword = ref('')
|
||||
const selected = ref(null)
|
||||
const results = ref([])
|
||||
const dropdown = ref(null)
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
const toggle = () => {
|
||||
dropdown.value.toggle()
|
||||
}
|
||||
|
||||
const onClose = () => emit('close')
|
||||
|
||||
const fetchResults = async (kw) => {
|
||||
if (!kw) return []
|
||||
const res = await fetch(`${API_BASE_URL}/api/search/users?keyword=${encodeURIComponent(kw)}`)
|
||||
if (!res.ok) return []
|
||||
const data = await res.json()
|
||||
results.value = data.map((u) => ({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
avatar: u.avatar,
|
||||
introduction: u.introduction,
|
||||
}))
|
||||
return results.value
|
||||
}
|
||||
|
||||
const highlight = (text) => {
|
||||
text = stripMarkdown(text || '')
|
||||
if (!keyword.value) return text
|
||||
const reg = new RegExp(keyword.value, 'gi')
|
||||
return text.replace(reg, (m) => `<span class="highlight">${m}</span>`)
|
||||
}
|
||||
|
||||
const handleAvatarError = (e) => {
|
||||
e.target.src = '/default-avatar.svg'
|
||||
}
|
||||
|
||||
watch(selected, async (val) => {
|
||||
if (!val) return
|
||||
const user = results.value.find((u) => u.id === val)
|
||||
if (!user) return
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
navigateTo('/login', { replace: true })
|
||||
} else {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/messages/conversations`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ recipientId: user.id }),
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
navigateTo(`/message-box/${data.conversationId}`, { replace: true })
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
selected.value = null
|
||||
keyword.value = ''
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
toggle,
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.search-dropdown {
|
||||
margin-top: 20px;
|
||||
width: 500px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
background-color: var(--app-menu-background-color);
|
||||
color: var(--text-color);
|
||||
border: none;
|
||||
outline: none;
|
||||
width: 100%;
|
||||
margin-left: 10px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.search-menu {
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.search-dropdown {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.search-option-item {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.search-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 20px;
|
||||
}
|
||||
|
||||
:deep(.highlight) {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.result-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.result-main {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.result-sub {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
</style>
|
||||
@@ -1,20 +1,22 @@
|
||||
<template>
|
||||
<div class="chat-container">
|
||||
<div v-if="!loading" class="chat-header">
|
||||
<div v-if="!loading && otherParticipant" class="chat-header">
|
||||
<NuxtLink to="/message-box" class="back-button">
|
||||
<i class="fas fa-arrow-left"></i>
|
||||
</NuxtLink>
|
||||
<h2 class="participant-name">{{ channel ? channel.name : otherParticipant?.username }}</h2>
|
||||
<h2 class="participant-name">{{ 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 }">
|
||||
@@ -26,6 +28,13 @@
|
||||
</div>
|
||||
</template>
|
||||
</BaseTimeline>
|
||||
<div class="empty-container">
|
||||
<BasePlaceholder
|
||||
v-if="messages.length === 0"
|
||||
text="暂无会话,发送消息试试 🎉"
|
||||
icon="fas fa-inbox"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -55,6 +64,7 @@ import { useWebSocket } from '~/composables/useWebSocket'
|
||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||
import TimeManager from '~/utils/time'
|
||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
@@ -65,7 +75,6 @@ let subscription = null
|
||||
|
||||
const messages = ref([])
|
||||
const participants = ref([])
|
||||
const channel = ref(null)
|
||||
const loading = ref(true)
|
||||
const sending = ref(false)
|
||||
const error = ref(null)
|
||||
@@ -127,7 +136,6 @@ async function fetchMessages(page = 0) {
|
||||
|
||||
if (page === 0) {
|
||||
participants.value = conversationData.participants
|
||||
channel.value = conversationData.channel
|
||||
}
|
||||
|
||||
// Since the backend sorts by descending, we need to reverse for correct chat order
|
||||
@@ -175,31 +183,25 @@ async function loadMoreMessages() {
|
||||
async function sendMessage(content, clearInput) {
|
||||
if (!content.trim()) return
|
||||
|
||||
const token = getToken()
|
||||
const recipient = otherParticipant.value
|
||||
if (!recipient) {
|
||||
toast.error('无法确定收信人')
|
||||
return
|
||||
}
|
||||
|
||||
sending.value = true
|
||||
const token = getToken()
|
||||
try {
|
||||
let url
|
||||
let body
|
||||
if (channel.value) {
|
||||
url = `${API_BASE_URL}/api/messages/conversations/${conversationId}/messages`
|
||||
body = { content: content }
|
||||
} else {
|
||||
const recipient = otherParticipant.value
|
||||
if (!recipient) {
|
||||
toast.error('无法确定收信人')
|
||||
sending.value = false
|
||||
return
|
||||
}
|
||||
url = `${API_BASE_URL}/api/messages`
|
||||
body = { recipientId: recipient.id, content: content }
|
||||
}
|
||||
const response = await fetch(url, {
|
||||
const response = await fetch(`${API_BASE_URL}/api/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify({
|
||||
recipientId: recipient.id,
|
||||
content: content,
|
||||
}),
|
||||
})
|
||||
if (!response.ok) throw new Error('发送失败')
|
||||
|
||||
@@ -390,27 +392,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 {
|
||||
@@ -466,7 +462,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;
|
||||
|
||||
@@ -1,105 +1,55 @@
|
||||
<template>
|
||||
<div class="messages-container">
|
||||
<div class="tabs">
|
||||
<div
|
||||
class="tab"
|
||||
:class="{ active: activeTab === 'messages' }"
|
||||
@click="activeTab = 'messages'"
|
||||
>
|
||||
站内信
|
||||
</div>
|
||||
<div
|
||||
class="tab"
|
||||
:class="{ active: activeTab === 'channels' }"
|
||||
@click="activeTab = 'channels'"
|
||||
>
|
||||
频道
|
||||
</div>
|
||||
<div v-if="loading" class="loading-message">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
|
||||
<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 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>
|
||||
|
||||
<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 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 v-else-if="error" class="error-container">
|
||||
<div class="error-text">{{ error }}</div>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div v-if="channelsLoading" class="loading-message">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
<div v-if="!loading" class="search-container">
|
||||
<SearchPersonDropdown />
|
||||
</div>
|
||||
|
||||
<div v-if="!loading && conversations.length === 0" class="empty-container">
|
||||
<BasePlaceholder v-if="conversations.length === 0" text="暂无会话" icon="fas fa-inbox" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!loading"
|
||||
v-for="convo in conversations"
|
||||
:key="convo.id"
|
||||
class="conversation-item"
|
||||
@click="goToConversation(convo.id)"
|
||||
>
|
||||
<div class="conversation-avatar">
|
||||
<img
|
||||
:src="getOtherParticipant(convo)?.avatar || '/default-avatar.svg'"
|
||||
:alt="getOtherParticipant(convo)?.username || '用户'"
|
||||
class="avatar-img"
|
||||
@error="handleAvatarError"
|
||||
/>
|
||||
</div>
|
||||
<div v-else-if="channelsError" class="error-container">
|
||||
<div class="error-text">{{ channelsError }}</div>
|
||||
</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 class="conversation-content">
|
||||
<div class="conversation-header">
|
||||
<div class="participant-name">{{ channel.name }}</div>
|
||||
|
||||
<div class="conversation-content">
|
||||
<div class="conversation-header">
|
||||
<div class="participant-name">
|
||||
{{ getOtherParticipant(convo)?.username || '未知用户' }}
|
||||
</div>
|
||||
<div class="last-message-row">
|
||||
<div class="last-message">{{ channel.description }}</div>
|
||||
<div class="message-time">
|
||||
{{ formatTime(convo.lastMessage?.createdAt || convo.createdAt) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
@@ -116,15 +66,13 @@ import { useWebSocket } from '~/composables/useWebSocket'
|
||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||
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 activeTab = ref('messages')
|
||||
const conversations = ref([])
|
||||
const loading = ref(true)
|
||||
const error = ref(null)
|
||||
const channels = ref([])
|
||||
const channelsLoading = ref(true)
|
||||
const channelsError = ref(null)
|
||||
const router = useRouter()
|
||||
const currentUser = ref(null)
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
@@ -147,7 +95,7 @@ async function fetchConversations() {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
conversations.value = data.filter((c) => !c.channel)
|
||||
conversations.value = data
|
||||
} catch (e) {
|
||||
error.value = '无法加载会话列表。'
|
||||
} finally {
|
||||
@@ -155,28 +103,6 @@ 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) {
|
||||
if (!currentUser.value || !conversation.participants) return null
|
||||
@@ -200,7 +126,6 @@ onActivated(async () => {
|
||||
|
||||
if (currentUser.value) {
|
||||
await fetchConversations()
|
||||
await fetchChannels()
|
||||
refreshGlobalUnreadCount() // Refresh global count when entering the list
|
||||
const token = getToken()
|
||||
if (token && !isConnected.value) {
|
||||
@@ -222,7 +147,6 @@ watch(isConnected, (newValue) => {
|
||||
|
||||
subscription = subscribe(destination, (message) => {
|
||||
fetchConversations()
|
||||
fetchChannels()
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -237,19 +161,6 @@ onUnmounted(() => {
|
||||
function goToConversation(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>
|
||||
|
||||
<style scoped>
|
||||
@@ -258,22 +169,6 @@ async function goToChannel(channel) {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 8px 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
border-bottom: 2px solid var(--primary-color);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.loading-message {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
@@ -281,6 +176,10 @@ async function goToChannel(channel) {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.search-container {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.messages-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
@@ -392,16 +291,6 @@ async function goToChannel(channel) {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.unread-dot {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background-color: #f56c6c;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.messages-container {
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user