Compare commits
2 Commits
6fde4bbc0d
...
f3137493af
| Author | SHA1 | Date | |
|---|---|---|---|
| f3137493af | |||
| 0f1684b8d7 |
@@ -1,4 +1,4 @@
|
||||
VITE_API_BASE_URL=/api/v1
|
||||
VITE_GAME_WS_URL=/ws
|
||||
VITE_API_PROXY_TARGET=http://192.168.1.5:19000
|
||||
VITE_WS_PROXY_TARGET=http://192.168.1.5:19000
|
||||
VITE_API_PROXY_TARGET=http://127.0.0.1:19000
|
||||
VITE_WS_PROXY_TARGET=http://127.0.0.1:19000
|
||||
|
||||
263
src/api/auth.ts
263
src/api/auth.ts
@@ -1,26 +1,26 @@
|
||||
export interface AuthUser {
|
||||
id?: string | number
|
||||
username?: string
|
||||
nickname?: string
|
||||
id?: string | number
|
||||
username?: string
|
||||
nickname?: string
|
||||
}
|
||||
|
||||
export interface AuthSessionInput {
|
||||
token: string
|
||||
tokenType?: string
|
||||
refreshToken?: string
|
||||
token: string
|
||||
tokenType?: string
|
||||
refreshToken?: string
|
||||
}
|
||||
|
||||
export interface AuthResult {
|
||||
token: string
|
||||
tokenType?: string
|
||||
refreshToken?: string
|
||||
expiresIn?: number
|
||||
user?: AuthUser
|
||||
token: string
|
||||
tokenType?: string
|
||||
refreshToken?: string
|
||||
expiresIn?: number
|
||||
user?: AuthUser
|
||||
}
|
||||
|
||||
interface ApiErrorPayload {
|
||||
message?: string
|
||||
error?: string
|
||||
message?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL ?? '').trim().replace(/\/$/, '')
|
||||
@@ -30,165 +30,178 @@ const REFRESH_PATH = import.meta.env.VITE_REFRESH_PATH ?? '/api/v1/auth/refresh'
|
||||
const LOGIN_BEARER_TOKEN = (import.meta.env.VITE_LOGIN_BEARER_TOKEN ?? '').trim()
|
||||
|
||||
function buildUrl(path: string): string {
|
||||
if (/^https?:\/\//.test(path)) {
|
||||
return path
|
||||
}
|
||||
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`
|
||||
if (!API_BASE_URL) {
|
||||
return normalizedPath
|
||||
}
|
||||
|
||||
if (API_BASE_URL.startsWith('/')) {
|
||||
const basePath = API_BASE_URL.startsWith('/') ? API_BASE_URL : `/${API_BASE_URL}`
|
||||
if (normalizedPath === basePath || normalizedPath.startsWith(`${basePath}/`)) {
|
||||
return normalizedPath
|
||||
if (/^https?:\/\//.test(path)) {
|
||||
return path
|
||||
}
|
||||
|
||||
return `${basePath}${normalizedPath}`
|
||||
}
|
||||
|
||||
// Avoid duplicated API prefix, e.g. base: /api/v1 + path: /api/v1/auth/login
|
||||
try {
|
||||
const baseUrl = new URL(API_BASE_URL)
|
||||
const basePath = baseUrl.pathname.replace(/\/$/, '')
|
||||
if (basePath && normalizedPath.startsWith(`${basePath}/`)) {
|
||||
return `${API_BASE_URL}${normalizedPath.slice(basePath.length)}`
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`
|
||||
if (!API_BASE_URL) {
|
||||
return normalizedPath
|
||||
}
|
||||
} catch {
|
||||
// API_BASE_URL may be a relative path; fallback to direct join.
|
||||
}
|
||||
|
||||
return `${API_BASE_URL}${normalizedPath}`
|
||||
if (API_BASE_URL.startsWith('/')) {
|
||||
const basePath = API_BASE_URL.startsWith('/') ? API_BASE_URL : `/${API_BASE_URL}`
|
||||
if (normalizedPath === basePath || normalizedPath.startsWith(`${basePath}/`)) {
|
||||
return normalizedPath
|
||||
}
|
||||
|
||||
return `${basePath}${normalizedPath}`
|
||||
}
|
||||
|
||||
// Avoid duplicated API prefix, e.g. base: /api/v1 + path: /api/v1/auth/login
|
||||
try {
|
||||
const baseUrl = new URL(API_BASE_URL)
|
||||
const basePath = baseUrl.pathname.replace(/\/$/, '')
|
||||
if (basePath && normalizedPath.startsWith(`${basePath}/`)) {
|
||||
return `${API_BASE_URL}${normalizedPath.slice(basePath.length)}`
|
||||
}
|
||||
} catch {
|
||||
// API_BASE_URL may be a relative path; fallback to direct join.
|
||||
}
|
||||
|
||||
return `${API_BASE_URL}${normalizedPath}`
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
url: string,
|
||||
body: Record<string, unknown>,
|
||||
extraHeaders?: Record<string, string>,
|
||||
url: string,
|
||||
body: Record<string, unknown>,
|
||||
extraHeaders?: Record<string, string>,
|
||||
): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...extraHeaders,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...extraHeaders,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
const payload = (await response.json().catch(() => ({}))) as T & ApiErrorPayload
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.message ?? payload.error ?? '请求失败,请稍后再试')
|
||||
}
|
||||
const payload = (await response.json().catch(() => ({}))) as T & ApiErrorPayload
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.message ?? payload.error ?? '请求失败,请稍后再试')
|
||||
}
|
||||
|
||||
return payload
|
||||
return payload
|
||||
}
|
||||
|
||||
function createAuthHeader(token: string, tokenType = 'Bearer'): string {
|
||||
const normalizedToken = token.trim()
|
||||
if (/^\S+\s+\S+/.test(normalizedToken)) {
|
||||
return normalizedToken
|
||||
}
|
||||
const normalizedToken = token.trim()
|
||||
if (/^\S+\s+\S+/.test(normalizedToken)) {
|
||||
return normalizedToken
|
||||
}
|
||||
|
||||
return `${tokenType || 'Bearer'} ${normalizedToken}`
|
||||
return `${tokenType || 'Bearer'} ${normalizedToken}`
|
||||
}
|
||||
|
||||
function extractToken(payload: Record<string, unknown>): string {
|
||||
const candidate =
|
||||
payload.token ??
|
||||
payload.accessToken ??
|
||||
payload.access_token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.accessToken ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.access_token
|
||||
const candidate =
|
||||
payload.token ??
|
||||
payload.accessToken ??
|
||||
payload.access_token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.accessToken ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.access_token
|
||||
|
||||
if (typeof candidate !== 'string' || candidate.length === 0) {
|
||||
throw new Error('登录成功,但后端未返回 token 字段')
|
||||
}
|
||||
if (typeof candidate !== 'string' || candidate.length === 0) {
|
||||
throw new Error('登录成功,但后端未返回 token 字段')
|
||||
}
|
||||
|
||||
return candidate
|
||||
return candidate
|
||||
}
|
||||
|
||||
function extractTokenType(payload: Record<string, unknown>): string | undefined {
|
||||
const candidate =
|
||||
payload.token_type ??
|
||||
payload.tokenType ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.token_type ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.tokenType
|
||||
const candidate =
|
||||
payload.token_type ??
|
||||
payload.tokenType ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.token_type ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.tokenType
|
||||
|
||||
return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined
|
||||
return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined
|
||||
}
|
||||
|
||||
function extractRefreshToken(payload: Record<string, unknown>): string | undefined {
|
||||
const candidate =
|
||||
payload.refresh_token ??
|
||||
payload.refreshToken ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.refresh_token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.refreshToken
|
||||
const candidate =
|
||||
payload.refresh_token ??
|
||||
payload.refreshToken ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.refresh_token ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.refreshToken
|
||||
|
||||
return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined
|
||||
return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined
|
||||
}
|
||||
|
||||
function extractExpiresIn(payload: Record<string, unknown>): number | undefined {
|
||||
const candidate =
|
||||
payload.expires_in ??
|
||||
payload.expiresIn ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.expires_in ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.expiresIn
|
||||
const candidate =
|
||||
payload.expires_in ??
|
||||
payload.expiresIn ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.expires_in ??
|
||||
(payload.data as Record<string, unknown> | undefined)?.expiresIn
|
||||
|
||||
return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : undefined
|
||||
return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : undefined
|
||||
}
|
||||
|
||||
function extractUser(payload: Record<string, unknown>): AuthUser | undefined {
|
||||
const user = payload.user ?? (payload.data as Record<string, unknown> | undefined)?.user
|
||||
return typeof user === 'object' && user !== null ? (user as AuthUser) : undefined
|
||||
const user = payload.user ?? (payload.data as Record<string, unknown> | undefined)?.user
|
||||
return typeof user === 'object' && user !== null ? (user as AuthUser) : undefined
|
||||
}
|
||||
|
||||
function parseAuthResult(payload: Record<string, unknown>): AuthResult {
|
||||
return {
|
||||
token: extractToken(payload),
|
||||
tokenType: extractTokenType(payload),
|
||||
refreshToken: extractRefreshToken(payload),
|
||||
expiresIn: extractExpiresIn(payload),
|
||||
user: extractUser(payload),
|
||||
}
|
||||
return {
|
||||
token: extractToken(payload),
|
||||
tokenType: extractTokenType(payload),
|
||||
refreshToken: extractRefreshToken(payload),
|
||||
expiresIn: extractExpiresIn(payload),
|
||||
user: extractUser(payload),
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(input: {
|
||||
username: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
username: string
|
||||
phone: string
|
||||
email: string
|
||||
password: string
|
||||
}): Promise<void> {
|
||||
await request<Record<string, unknown>>(buildUrl(REGISTER_PATH), input)
|
||||
await request<Record<string, unknown>>(buildUrl(REGISTER_PATH), input)
|
||||
}
|
||||
|
||||
export async function login(input: { loginId: string; password: string }): Promise<AuthResult> {
|
||||
const payload = await request<Record<string, unknown>>(
|
||||
buildUrl(LOGIN_PATH),
|
||||
{
|
||||
login_id: input.loginId,
|
||||
password: input.password,
|
||||
},
|
||||
LOGIN_BEARER_TOKEN ? { Authorization: `Bearer ${LOGIN_BEARER_TOKEN}` } : undefined,
|
||||
)
|
||||
return parseAuthResult(payload)
|
||||
const payload = await request<Record<string, unknown>>(
|
||||
buildUrl(LOGIN_PATH),
|
||||
{
|
||||
login_id: input.loginId,
|
||||
password: input.password,
|
||||
},
|
||||
LOGIN_BEARER_TOKEN ? {Authorization: `Bearer ${LOGIN_BEARER_TOKEN}`} : undefined,
|
||||
)
|
||||
return parseAuthResult(payload)
|
||||
}
|
||||
|
||||
export async function refreshAccessToken(input: AuthSessionInput): Promise<AuthResult> {
|
||||
if (!input.refreshToken) {
|
||||
throw new Error('缺少 refresh_token,无法刷新登录状态')
|
||||
}
|
||||
if (!input.refreshToken) {
|
||||
throw new Error('缺少 refresh_token,无法刷新登录状态')
|
||||
}
|
||||
|
||||
const payload = await request<Record<string, unknown>>(
|
||||
buildUrl(REFRESH_PATH),
|
||||
{
|
||||
refreshToken: input.refreshToken,
|
||||
},
|
||||
{
|
||||
Authorization: createAuthHeader(input.token, input.tokenType),
|
||||
},
|
||||
)
|
||||
const refreshBody = {
|
||||
refreshToken: input.refreshToken
|
||||
}
|
||||
|
||||
return parseAuthResult(payload)
|
||||
// 兼容不同后端实现:
|
||||
// 1) 有的要求 Authorization + refresh token
|
||||
// 2) 有的只接受 refresh token,不接受 Authorization
|
||||
let payload: Record<string, unknown>
|
||||
try {
|
||||
payload = await request<Record<string, unknown>>(
|
||||
buildUrl(REFRESH_PATH),
|
||||
refreshBody,
|
||||
{
|
||||
Authorization: createAuthHeader(input.token, input.tokenType),
|
||||
},
|
||||
)
|
||||
} catch {
|
||||
payload = await request<Record<string, unknown>>(
|
||||
buildUrl(REFRESH_PATH),
|
||||
refreshBody,
|
||||
)
|
||||
}
|
||||
|
||||
return parseAuthResult(payload)
|
||||
}
|
||||
|
||||
BIN
src/assets/images/direction/bei.png
Executable file
BIN
src/assets/images/direction/bei.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
BIN
src/assets/images/direction/dong.png
Executable file
BIN
src/assets/images/direction/dong.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
BIN
src/assets/images/direction/nan.png
Executable file
BIN
src/assets/images/direction/nan.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 5.6 KiB |
BIN
src/assets/images/direction/xi.png
Executable file
BIN
src/assets/images/direction/xi.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
1
src/assets/images/icons/triangle.svg
Normal file
1
src/assets/images/icons/triangle.svg
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1774491457300" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6759" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M535.466667 812.8l450.133333-563.2c14.933333-19.2 2.133333-49.066667-23.466667-49.066667H61.866667c-25.6 0-38.4 29.866667-23.466667 49.066667l450.133333 563.2c12.8 14.933333 34.133333 14.933333 46.933334 0z" fill="#ffffff" p-id="6760"></path></svg>
|
||||
|
After Width: | Height: | Size: 581 B |
@@ -566,6 +566,15 @@
|
||||
left: 110px;
|
||||
}
|
||||
|
||||
.center-wind-square {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 3;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.center-desk {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
|
||||
151
src/components/game/WindSquare.vue
Normal file
151
src/components/game/WindSquare.vue
Normal file
@@ -0,0 +1,151 @@
|
||||
<script setup lang="ts">
|
||||
import triangleIcon from '../../assets/images/icons/triangle.svg'
|
||||
|
||||
defineProps<{
|
||||
seatWinds: {
|
||||
top: string
|
||||
right: string
|
||||
bottom: string
|
||||
left: string
|
||||
}
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="wind-square">
|
||||
<img class="triangle top" :src="triangleIcon" alt="" />
|
||||
<img class="triangle right" :src="triangleIcon" alt="" />
|
||||
<img class="triangle bottom" :src="triangleIcon" alt="" />
|
||||
<img class="triangle left" :src="triangleIcon" alt="" />
|
||||
|
||||
<span class="wind-slot wind-top">
|
||||
<img class="wind-icon" :src="seatWinds.top" alt="北位风" />
|
||||
</span>
|
||||
<span class="wind-slot wind-right">
|
||||
<img class="wind-icon" :src="seatWinds.right" alt="右位风" />
|
||||
</span>
|
||||
<span class="wind-slot wind-bottom">
|
||||
<img class="wind-icon" :src="seatWinds.bottom" alt="本位风" />
|
||||
</span>
|
||||
<span class="wind-slot wind-left">
|
||||
<img class="wind-icon" :src="seatWinds.left" alt="左位风" />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wind-square {
|
||||
position: relative;
|
||||
width: 128px;
|
||||
height: 128px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.wind-square::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 18px;
|
||||
border-radius: 10px;
|
||||
background:
|
||||
radial-gradient(circle at 50% 45%, rgba(244, 222, 151, 0.2), rgba(12, 40, 30, 0.05) 65%),
|
||||
linear-gradient(145deg, rgba(21, 82, 58, 0.42), rgba(8, 38, 27, 0.16));
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 225, 165, 0.15),
|
||||
0 6px 12px rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.triangle {
|
||||
position: absolute;
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
object-fit: contain;
|
||||
opacity: 0.96;
|
||||
filter: drop-shadow(0 3px 6px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.triangle.top {
|
||||
top: 4px;
|
||||
left: 32px;
|
||||
transform: rotate(0deg);
|
||||
filter:
|
||||
hue-rotate(-8deg)
|
||||
saturate(1.35)
|
||||
brightness(1.1)
|
||||
drop-shadow(0 3px 6px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.triangle.right {
|
||||
top: 32px;
|
||||
right: 4px;
|
||||
transform: rotate(90deg);
|
||||
filter:
|
||||
hue-rotate(16deg)
|
||||
saturate(1.28)
|
||||
brightness(1.08)
|
||||
drop-shadow(0 3px 6px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.triangle.bottom {
|
||||
bottom: 4px;
|
||||
left: 32px;
|
||||
transform: rotate(180deg);
|
||||
filter:
|
||||
hue-rotate(34deg)
|
||||
saturate(1.2)
|
||||
brightness(1.02)
|
||||
drop-shadow(0 3px 6px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.triangle.left {
|
||||
top: 32px;
|
||||
left: 4px;
|
||||
transform: rotate(270deg);
|
||||
filter:
|
||||
hue-rotate(-26deg)
|
||||
saturate(1.24)
|
||||
brightness(1.06)
|
||||
drop-shadow(0 3px 6px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.wind-slot {
|
||||
position: absolute;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9px;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 237, 186, 0.92), rgba(232, 191, 105, 0.84));
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.56),
|
||||
0 3px 8px rgba(0, 0, 0, 0.26);
|
||||
}
|
||||
|
||||
.wind-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2));
|
||||
}
|
||||
|
||||
.wind-top {
|
||||
top: 12px;
|
||||
left: 48px;
|
||||
}
|
||||
|
||||
.wind-right {
|
||||
top: 48px;
|
||||
right: 12px;
|
||||
}
|
||||
|
||||
.wind-bottom {
|
||||
bottom: 12px;
|
||||
left: 48px;
|
||||
}
|
||||
|
||||
.wind-left {
|
||||
top: 48px;
|
||||
left: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -16,11 +16,17 @@ import TopPlayerCard from '../components/game/TopPlayerCard.vue'
|
||||
import RightPlayerCard from '../components/game/RightPlayerCard.vue'
|
||||
import BottomPlayerCard from '../components/game/BottomPlayerCard.vue'
|
||||
import LeftPlayerCard from '../components/game/LeftPlayerCard.vue'
|
||||
import WindSquare from '../components/game/WindSquare.vue'
|
||||
import eastWind from '../assets/images/direction/dong.png'
|
||||
import southWind from '../assets/images/direction/nan.png'
|
||||
import westWind from '../assets/images/direction/xi.png'
|
||||
import northWind from '../assets/images/direction/bei.png'
|
||||
import type {SeatPlayerCardModel} from '../components/game/seat-player-card'
|
||||
import type {SeatKey} from '../game/seat'
|
||||
import type {GameAction} from '../game/actions'
|
||||
import {dispatchGameAction} from '../game/dispatcher'
|
||||
import {readStoredAuth} from '../utils/auth-storage'
|
||||
import {refreshAccessToken} from '../api/auth'
|
||||
import {clearAuth, readStoredAuth, writeStoredAuth} from '../utils/auth-storage'
|
||||
import type {WsStatus} from '../ws/client'
|
||||
import {wsClient} from '../ws/client'
|
||||
import {sendWsMessage} from '../ws/sender'
|
||||
@@ -64,6 +70,8 @@ const isTrustMode = ref(false)
|
||||
const menuTriggerActive = ref(false)
|
||||
let menuTriggerTimer: number | null = null
|
||||
let menuOpenTimer: number | null = null
|
||||
let refreshingWsToken = false
|
||||
let lastForcedRefreshAt = 0
|
||||
|
||||
const loggedInUserId = computed(() => {
|
||||
const rawId = auth.value?.user?.id
|
||||
@@ -173,6 +181,28 @@ const seatViews = computed<SeatViewModel[]>(() => {
|
||||
})
|
||||
})
|
||||
|
||||
const seatWinds = computed<Record<SeatKey, string>>(() => {
|
||||
const tableOrder: SeatKey[] = ['bottom', 'right', 'top', 'left']
|
||||
const players = gamePlayers.value
|
||||
const selfSeatIndex = myPlayer.value?.seatIndex ?? players.find((player) => player.playerId === loggedInUserId.value)?.seatIndex ?? 0
|
||||
|
||||
const directionBySeatIndex = [eastWind, southWind, westWind, northWind]
|
||||
const result: Record<SeatKey, string> = {
|
||||
top: northWind,
|
||||
right: eastWind,
|
||||
bottom: southWind,
|
||||
left: westWind,
|
||||
}
|
||||
|
||||
for (let absoluteSeat = 0; absoluteSeat < 4; absoluteSeat += 1) {
|
||||
const relativeIndex = (absoluteSeat - selfSeatIndex + 4) % 4
|
||||
const seatKey = tableOrder[relativeIndex] ?? 'top'
|
||||
result[seatKey] = directionBySeatIndex[absoluteSeat] ?? northWind
|
||||
}
|
||||
|
||||
return result
|
||||
})
|
||||
|
||||
const rightMessages = computed(() => wsMessages.value.slice(-16).reverse())
|
||||
|
||||
const currentPhaseText = computed(() => {
|
||||
@@ -255,13 +285,13 @@ const seatDecor = computed<Record<SeatKey, SeatPlayerCardModel>>(() => {
|
||||
|
||||
const displayName = seat.player.displayName || `玩家${seat.player.seatIndex + 1}`
|
||||
const avatarUrl = seat.isSelf
|
||||
? (localCachedAvatarUrl.value || seat.player.avatarURL || '')
|
||||
: (seat.player.avatarURL || '')
|
||||
? (localCachedAvatarUrl.value || seat.player.avatarURL || '')
|
||||
: (seat.player.avatarURL || '')
|
||||
const selfDisplayName = seat.player.displayName || loggedInUserName.value || '你自己'
|
||||
|
||||
result[seat.key] = {
|
||||
avatarUrl,
|
||||
name: seat.isSelf ? selfDisplayName : displayName,
|
||||
name: Array.from(seat.isSelf ? selfDisplayName : displayName).slice(0, 4).join(''),
|
||||
dealer: seat.player.seatIndex === dealerIndex,
|
||||
isTurn: seat.isTurn,
|
||||
missingSuitLabel: missingSuitLabel(seat.player.missingSuit),
|
||||
@@ -409,26 +439,106 @@ function toGameAction(message: unknown): GameAction | null {
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWsConnected(): void {
|
||||
const token = auth.value?.token
|
||||
function logoutToLogin(): void {
|
||||
clearAuth()
|
||||
auth.value = null
|
||||
wsClient.close()
|
||||
void router.replace('/login')
|
||||
}
|
||||
|
||||
function decodeJwtExpMs(token: string): number | null {
|
||||
const parts = token.split('.')
|
||||
const payloadPart = parts[1]
|
||||
if (!payloadPart) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const normalized = payloadPart.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
||||
const payload = JSON.parse(window.atob(padded)) as { exp?: number }
|
||||
return typeof payload.exp === 'number' ? payload.exp * 1000 : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function shouldRefreshWsToken(token: string): boolean {
|
||||
const expMs = decodeJwtExpMs(token)
|
||||
if (!expMs) {
|
||||
return false
|
||||
}
|
||||
|
||||
return expMs <= Date.now() + 30_000
|
||||
}
|
||||
|
||||
async function resolveWsToken(forceRefresh = false, logoutOnRefreshFail = false): Promise<string | null> {
|
||||
const current = auth.value
|
||||
if (!current?.token) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!forceRefresh && !shouldRefreshWsToken(current.token)) {
|
||||
return current.token
|
||||
}
|
||||
|
||||
if (!current.refreshToken || refreshingWsToken) {
|
||||
return current.token
|
||||
}
|
||||
|
||||
refreshingWsToken = true
|
||||
try {
|
||||
const refreshed = await refreshAccessToken({
|
||||
token: current.token,
|
||||
tokenType: current.tokenType,
|
||||
refreshToken: current.refreshToken,
|
||||
})
|
||||
|
||||
const nextAuth = {
|
||||
...current,
|
||||
token: refreshed.token,
|
||||
tokenType: refreshed.tokenType ?? current.tokenType,
|
||||
refreshToken: refreshed.refreshToken ?? current.refreshToken,
|
||||
expiresIn: refreshed.expiresIn,
|
||||
}
|
||||
auth.value = nextAuth
|
||||
writeStoredAuth(nextAuth)
|
||||
return nextAuth.token
|
||||
} catch {
|
||||
if (logoutOnRefreshFail) {
|
||||
logoutToLogin()
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
refreshingWsToken = false
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureWsConnected(forceRefresh = false): Promise<void> {
|
||||
const token = await resolveWsToken(forceRefresh, false)
|
||||
if (!token) {
|
||||
wsError.value = '未找到登录凭证,无法建立连接'
|
||||
return
|
||||
}
|
||||
|
||||
wsError.value = ''
|
||||
wsClient.connect(buildWsUrl(token), token)
|
||||
wsClient.connect(buildWsUrl(), token)
|
||||
}
|
||||
|
||||
async function reconnectWsInternal(forceRefresh = false): Promise<boolean> {
|
||||
const token = await resolveWsToken(forceRefresh, false)
|
||||
if (!token) {
|
||||
wsError.value = '未找到登录凭证,无法建立连接'
|
||||
return false
|
||||
}
|
||||
|
||||
wsError.value = ''
|
||||
wsClient.reconnect(buildWsUrl(), token)
|
||||
return true
|
||||
}
|
||||
|
||||
function reconnectWs(): void {
|
||||
const token = auth.value?.token
|
||||
if (!token) {
|
||||
wsError.value = '未找到登录凭证,无法建立连接'
|
||||
return
|
||||
}
|
||||
|
||||
wsError.value = ''
|
||||
wsClient.reconnect(buildWsUrl(token), token)
|
||||
void reconnectWsInternal()
|
||||
}
|
||||
|
||||
function backHall(): void {
|
||||
@@ -537,10 +647,25 @@ onMounted(() => {
|
||||
wsClient.onError((message: string) => {
|
||||
wsError.value = message
|
||||
wsMessages.value.push(`[error] ${message}`)
|
||||
|
||||
// WebSocket 握手失败时浏览器拿不到 401 状态码,统一按需强制刷新 token 后重连一次
|
||||
const nowMs = Date.now()
|
||||
if (nowMs - lastForcedRefreshAt > 5000) {
|
||||
lastForcedRefreshAt = nowMs
|
||||
void resolveWsToken(true, true).then((refreshedToken) => {
|
||||
if (!refreshedToken) {
|
||||
return
|
||||
}
|
||||
wsError.value = ''
|
||||
wsClient.reconnect(buildWsUrl(), refreshedToken)
|
||||
}).catch(() => {
|
||||
logoutToLogin()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
unsubscribe = wsClient.onStatusChange(handler)
|
||||
ensureWsConnected()
|
||||
void ensureWsConnected()
|
||||
|
||||
clockTimer = window.setInterval(() => {
|
||||
now.value = Date.now()
|
||||
@@ -669,6 +794,8 @@ onBeforeUnmount(() => {
|
||||
<span>{{ seatDecor.right.missingSuitLabel }}</span>
|
||||
</div>
|
||||
|
||||
<WindSquare class="center-wind-square" :seat-winds="seatWinds"/>
|
||||
|
||||
|
||||
<div class="bottom-control-panel">
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ function connectGameWs(): void {
|
||||
if (!token) {
|
||||
return
|
||||
}
|
||||
wsClient.connect(buildWsUrl(token), token)
|
||||
wsClient.connect(buildWsUrl(), token)
|
||||
}
|
||||
|
||||
async function refreshRooms(): Promise<void> {
|
||||
|
||||
@@ -38,10 +38,15 @@ class WsClient {
|
||||
private buildUrl(): string {
|
||||
if (!this.token) return this.url
|
||||
|
||||
const hasQuery = this.url.includes('?')
|
||||
const connector = hasQuery ? '&' : '?'
|
||||
|
||||
return `${this.url}${connector}token=${encodeURIComponent(this.token)}`
|
||||
try {
|
||||
const parsed = new URL(this.url)
|
||||
parsed.searchParams.set('token', this.token)
|
||||
return parsed.toString()
|
||||
} catch {
|
||||
const hasQuery = this.url.includes('?')
|
||||
const connector = hasQuery ? '&' : '?'
|
||||
return `${this.url}${connector}token=${encodeURIComponent(this.token)}`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const WS_BASE_URL = import.meta.env.VITE_GAME_WS_URL ?? '/api/v1/ws'
|
||||
|
||||
export function buildWsUrl(token: string): string {
|
||||
export function buildWsUrl(): string {
|
||||
const baseUrl = /^wss?:\/\//.test(WS_BASE_URL)
|
||||
? new URL(WS_BASE_URL)
|
||||
: new URL(
|
||||
@@ -8,6 +8,5 @@ export function buildWsUrl(token: string): string {
|
||||
`${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}`,
|
||||
)
|
||||
|
||||
baseUrl.searchParams.set('token', token)
|
||||
return baseUrl.toString()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user