Compare commits

...

20 Commits

Author SHA1 Message Date
Tim
8ee1347b17 Merge branch 'feature/daily_bugfix_0823' into codex/create-searchpersondropdown-component 2025-08-23 01:06:11 +08:00
Tim
7e95120341 feat: add person search dropdown 2025-08-23 01:05:28 +08:00
tim
2f261983ac fix: 暂无会话适配 2025-08-23 01:02:35 +08:00
tim
e8e7b9a245 feat: add search drop down 2025-08-23 00:53:32 +08:00
tim
d2bd949ac8 fix: 前端采用sockjs 2025-08-22 23:57:03 +08:00
tim
605654ec99 fix: 把原生 WS 与 SockJS 分路径,避免混淆 2025-08-22 23:52:53 +08:00
tim
88127fcf34 fix: 把原生 WS 与 SockJS 分路径,避免混淆 2025-08-22 23:51:42 +08:00
tim
0a82f0036b fix: 把原生 WS 与 SockJS 分路径,避免混淆 2025-08-22 23:46:58 +08:00
tim
3a979277e4 fix: registerStompEndpoints 里保留一次注册即可,一般写法是一次 addEndpoint("/api/ws") + .withSockJS(),并统一用 setAllowedOriginPatterns(...) 配置白名单,避免同一路径双注册引起歧义。 2025-08-22 23:35:15 +08:00
tim
1c582fbbf1 fix: WebSocketConfig:同时给 SockJS 注册设置允许的 Origin(endpoint 用 patterns,SockJS 用 exact) 2025-08-22 23:18:05 +08:00
tim
92452da19a fix: 改用 patterns,补齐 staging 域名(https) 2025-08-22 23:05:24 +08:00
tim
a2ccaae7aa fix: 改用 patterns,补齐 staging 域名(https) 2025-08-22 23:01:57 +08:00
tim
23371d4433 Revert "fix: 同源内嵌"
This reverts commit e05d65cf49.
2025-08-22 22:09:41 +08:00
tim
e05d65cf49 fix: 同源内嵌 2025-08-22 22:00:08 +08:00
Tim
aaf9b35a45 Merge pull request #698 from nagisa77/feature/daily_bugfix_0822_b
fix: api fix
2025-08-22 17:11:55 +08:00
Tim
61c0336a78 fix: api fix 2025-08-22 16:25:22 +08:00
Tim
69c913394f Merge pull request #697 from nagisa77/feature/daily_bugfix_0822_b
fix: 修复nginx /ws拦截问题
2025-08-22 15:27:10 +08:00
Tim
0ed9ad2f2a fix: 修复nginx /ws拦截问题 2025-08-22 15:26:41 +08:00
Tim
67e912381b Merge pull request #693 from nagisa77/feature/daily_bugfix_0822_a
fix: 发送信息,携带头像
2025-08-22 13:26:39 +08:00
Tim
d77baa8a93 Merge pull request #692 from nagisa77/feature/daily_bugfix_0822_a
fix: 移动端 ui适配
2025-08-22 13:24:01 +08:00
9 changed files with 379 additions and 130 deletions

View File

@@ -92,19 +92,20 @@ public class SecurityConfig {
cfg.setAllowedHeaders(List.of("*"));
cfg.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cfg);
source.registerCorsConfiguration("/api/**", cfg);
return source;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.cors(Customizer.withDefaults()) // 让 Spring 自带 CorsFilter 处理预检
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors(Customizer.withDefaults())
.headers(h -> h.frameOptions(f -> f.sameOrigin()))
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(eh -> eh.accessDeniedHandler(customAccessDeniedHandler))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/ws/**").permitAll()
.requestMatchers("/api/ws/**", "/api/sockjs/**").permitAll()
.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/comments/**").permitAll()
@@ -173,7 +174,8 @@ public class SecurityConfig {
response.getWriter().write("{\"error\": \"Invalid or expired token\"}");
return;
}
} else if (!uri.startsWith("/api/auth") && !publicGet && !uri.startsWith("/ws")) {
} else if (!uri.startsWith("/api/auth") && !publicGet
&& !uri.startsWith("/api/ws") && !uri.startsWith("/api/sockjs")) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"error\": \"Missing token\"}");

View File

@@ -41,28 +41,38 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Registers the "/ws" endpoint, enabling SockJS fallback options so that alternate transports may be used if WebSocket is not available.
registry.addEndpoint("/ws")
// 安全改进:使用具体的允许源,而不是通配符
.setAllowedOrigins(
"http://127.0.0.1:8080",
"http://127.0.0.1:3000",
"http://127.0.0.1:3001",
"http://127.0.0.1",
"http://localhost:8080",
"http://localhost:3000",
"http://localhost:3001",
"http://localhost",
"http://30.211.97.238:3000",
"http://30.211.97.238",
"http://192.168.7.98",
"http://192.168.7.98:3000",
websiteUrl,
websiteUrl.replace("://www.", "://")
// 1) 原生 WebSocket不带 SockJS
registry.addEndpoint("/api/ws")
.setAllowedOriginPatterns(
"https://staging.open-isle.com",
"https://www.staging.open-isle.com",
websiteUrl,
websiteUrl.replace("://www.", "://"),
"http://localhost:*",
"http://127.0.0.1:*",
"http://192.168.7.98:*",
"http://30.211.97.238:*"
);
// 2) SockJS 回退:单独路径
registry.addEndpoint("/api/sockjs")
.setAllowedOriginPatterns(
"https://staging.open-isle.com",
"https://www.staging.open-isle.com",
websiteUrl,
websiteUrl.replace("://www.", "://"),
"http://localhost:*",
"http://127.0.0.1:*",
"http://192.168.7.98:*",
"http://30.211.97.238:*"
)
.withSockJS();
.withSockJS()
.setWebSocketEnabled(true)
.setSessionCookieNeeded(false);
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {

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

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

@@ -1,85 +1,83 @@
import { ref } from 'vue';
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client/dist/sockjs.min.js';
import { useRuntimeConfig } from '#app';
import { ref } from 'vue'
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client/dist/sockjs.min.js'
import { useRuntimeConfig } from '#app'
const client = ref(null);
const isConnected = ref(false);
const client = ref(null)
const isConnected = ref(false)
const connect = (token) => {
if (isConnected.value) {
return;
}
if (isConnected.value) {
return
}
const config = useRuntimeConfig();
const API_BASE_URL = config.public.apiBaseUrl;
const socketUrl = `${API_BASE_URL}/ws`;
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const socketUrl = `${API_BASE_URL}/api/sockjs`
const socket = new SockJS(socketUrl);
const stompClient = new Client({
webSocketFactory: () => socket,
connectHeaders: {
Authorization: `Bearer ${token}`,
},
debug: function (str) {
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
const socket = new SockJS(socketUrl)
const stompClient = new Client({
webSocketFactory: () => socket,
connectHeaders: {
Authorization: `Bearer ${token}`,
},
debug: function (str) {},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
})
stompClient.onConnect = (frame) => {
isConnected.value = true;
};
stompClient.onConnect = (frame) => {
isConnected.value = true
}
stompClient.onStompError = (frame) => {
console.error('WebSocket STOMP error:', frame);
};
stompClient.onStompError = (frame) => {
console.error('WebSocket STOMP error:', frame)
}
stompClient.activate();
client.value = stompClient;
};
stompClient.activate()
client.value = stompClient
}
const disconnect = () => {
if (client.value) {
isConnected.value = false;
client.value.deactivate();
client.value = null;
}
};
if (client.value) {
isConnected.value = false
client.value.deactivate()
client.value = null
}
}
const subscribe = (destination, callback) => {
if (!isConnected.value || !client.value || !client.value.connected) {
return null;
}
if (!isConnected.value || !client.value || !client.value.connected) {
return null
}
try {
const subscription = client.value.subscribe(destination, (message) => {
try {
if (destination.includes('/queue/unread-count')) {
callback(message);
} else {
const parsedMessage = JSON.parse(message.body);
callback(parsedMessage);
}
} catch (error) {
callback(message);
}
});
return subscription;
} catch (error) {
return null;
}
};
try {
const subscription = client.value.subscribe(destination, (message) => {
try {
if (destination.includes('/queue/unread-count')) {
callback(message)
} else {
const parsedMessage = JSON.parse(message.body)
callback(parsedMessage)
}
} catch (error) {
callback(message)
}
})
return subscription
} catch (error) {
return null
}
}
export function useWebSocket() {
return {
client,
isConnected,
connect,
disconnect,
subscribe,
};
}
return {
client,
isConnected,
connect,
disconnect,
subscribe,
}
}

View File

@@ -8,13 +8,15 @@
</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()
@@ -281,7 +291,13 @@ watch(isConnected, (newValue) => {
subscription = subscribe(`/topic/conversation/${conversationId}`, (message) => {
// 避免重复显示当前用户发送的消息
if (message.sender.id !== currentUser.value.id) {
messages.value.push(message)
messages.value.push({
...message,
src: message.sender.avatar,
iconClick: () => {
navigateTo(`/users/${message.sender.id}`, { replace: true })
},
})
// 实时收到消息时自动标记为已读
markConversationAsRead()
setTimeout(() => {
@@ -376,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 {
@@ -452,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;

View File

@@ -8,11 +8,16 @@
<div class="error-text">{{ error }}</div>
</div>
<div v-else-if="conversations.length === 0" class="empty-container">
<div class="empty-text">暂无会话</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"
@@ -61,6 +66,8 @@ 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 conversations = ref([])
@@ -169,6 +176,10 @@ function goToConversation(id) {
height: 300px;
}
.search-container {
margin-bottom: 24px;
}
.messages-header {
margin-bottom: 24px;
}

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;