mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix: scope session state and confirm chat destinations
This commit is contained in:
1 parent
c16d1d4cfb
commit
db08fbda6b
18 files changed
+969
-206
No files matched your search
@@ -7,15 +7,16 @@ import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accom
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
|
||||
import { createScreenShareController } from "../voice/screen-share.js";
|
||||
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
|
||||
import { parseServerMessage } from "../../../src/shared/server-messages.js";
|
||||
import type { ChatMessage } from "../../../src/shared/voice-models.js";
|
||||
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
|
||||
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent } from "../../../src/shared/voice-models.js";
|
||||
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
|
||||
import { reactive, ref, shallowRef } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
@@ -189,11 +190,19 @@ class CancelledMediaOperation extends Error {
|
||||
export function useVoiceWebSocket() {
|
||||
const ws = shallowRef<WebSocket | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const members = reactive<ChannelMember[]>([]);
|
||||
const channels = reactive<ChannelInfo[]>([]);
|
||||
const chatMessages = reactive<ChatMessage[]>([]);
|
||||
const serverEvents = reactive<ServerEvent[]>([]);
|
||||
const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]);
|
||||
const sessionState = createVoiceSessionState({
|
||||
selfId: () => state.tsClientId,
|
||||
onMemberRemoved(id) {
|
||||
clearSpeaking(id);
|
||||
remotePlayback.clear(id);
|
||||
delete volumes[id];
|
||||
whisperTargetIds.delete(id);
|
||||
if (!whisperTargetIds.size) whisperActive.value = false;
|
||||
},
|
||||
onMembersChanged: syncKnownMemberVolumes,
|
||||
});
|
||||
const { members, channels, chatMessages, serverEvents, pokeNotifications } = sessionState;
|
||||
let chatGeneration = 0;
|
||||
const voiceConnection = createVoiceConnection({
|
||||
onSocket: socket => { ws.value = socket; },
|
||||
onMessage: handleMessage,
|
||||
@@ -203,6 +212,8 @@ export function useVoiceWebSocket() {
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
state.tsClientId = 0;
|
||||
if (!state.reconnectFailed) sessionState.reset();
|
||||
if (event.code !== 1000 && !state.reconnectFailed && !state.errorCode) {
|
||||
state.errorCode = closeErrorCode(event.code, event.reason);
|
||||
state.error = closeReason(event.code, event.reason);
|
||||
@@ -994,14 +1005,13 @@ export function useVoiceWebSocket() {
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
if (!keepRememberedIdentity) identityMaterial.value = "";
|
||||
members.length = 0;
|
||||
channels.length = 0;
|
||||
chatMessages.length = 0;
|
||||
sessionState.reset();
|
||||
for (const key of Object.keys(volumes)) delete volumes[Number(key)];
|
||||
}
|
||||
|
||||
/** All ways a session ends release the same owned media and pending work. */
|
||||
function releaseSessionResources(sendScreenStop = false): void {
|
||||
chatGeneration++;
|
||||
inputDeviceGeneration++;
|
||||
outputDeviceGeneration++;
|
||||
deviceListGeneration++;
|
||||
@@ -1022,7 +1032,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function handleMessage(raw: unknown): void {
|
||||
const msg = parseServerMessage(raw);
|
||||
if (!msg || screenShare.handleMessage(msg)) return;
|
||||
if (!msg || screenShare.handleMessage(msg) || sessionState.receive(msg)) return;
|
||||
switch (msg.type) {
|
||||
case "connected":
|
||||
const wasReconnecting = state.reconnecting;
|
||||
@@ -1041,16 +1051,8 @@ export function useVoiceWebSocket() {
|
||||
// native TeamSpeak users even before WebRTC negotiation completes.
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
sessionState.connected(msg);
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (Array.isArray(msg.members)) {
|
||||
members.length = 0;
|
||||
for (const member of msg.members) {
|
||||
members.push({ ...member, isSelf: Number(member.id) === state.tsClientId });
|
||||
}
|
||||
syncKnownMemberVolumes();
|
||||
}
|
||||
serverEvents.length = 0;
|
||||
if (Array.isArray(msg.serverEventLog)) serverEvents.push(...msg.serverEventLog);
|
||||
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
|
||||
identityMaterial.value = msg.identity;
|
||||
if (lastConnection) lastConnection.identity = msg.identity;
|
||||
@@ -1069,71 +1071,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
screenShare.refreshStreams();
|
||||
break;
|
||||
case "memberEnter":
|
||||
if (!members.some((member) => member.id === msg.id)) {
|
||||
members.push({ id: msg.id, nickname: msg.nickname, uid: typeof msg.uid === "string" ? msg.uid : undefined, avatar: typeof msg.avatar === "string" ? msg.avatar : undefined, isSelf: Boolean(msg.isSelf) });
|
||||
syncKnownMemberVolumes();
|
||||
}
|
||||
break;
|
||||
case "memberLeave": {
|
||||
const clientId = Number(msg.id);
|
||||
clearSpeaking(clientId);
|
||||
remotePlayback.clear(clientId);
|
||||
const index = members.findIndex((member) => member.id === clientId);
|
||||
if (index >= 0) members.splice(index, 1);
|
||||
break;
|
||||
}
|
||||
case "channelList":
|
||||
channels.length = 0;
|
||||
if (Array.isArray(msg.channels)) {
|
||||
for (const channel of msg.channels) channels.push(channel);
|
||||
}
|
||||
syncKnownMemberVolumes();
|
||||
break;
|
||||
case "memberAvatar": {
|
||||
const clientId = Number(msg.id);
|
||||
const uid = typeof msg.uid === "string" ? msg.uid : "";
|
||||
const avatar = typeof msg.avatar === "string" ? msg.avatar : "";
|
||||
const member = members.find((candidate) => candidate.id === clientId && (!uid || candidate.uid === uid));
|
||||
if (member) member.avatar = avatar || undefined;
|
||||
for (const channel of channels) {
|
||||
const channelMember = channel.members?.find((candidate) => candidate.id === clientId && (!uid || candidate.uid === uid));
|
||||
if (channelMember) channelMember.avatar = avatar || undefined;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "chatMessage":
|
||||
if (Number(msg.invokerId) === state.tsClientId) break;
|
||||
const incomingScope = msg.scope === "private" || msg.scope === "server" || msg.scope === "channel" ? msg.scope : "system";
|
||||
const rawTargetId = typeof msg.targetId === "string" || typeof msg.targetId === "number" ? String(msg.targetId) : undefined;
|
||||
// Older gateways and TeamSpeak channel notifications may use 0 as
|
||||
// the broadcast sentinel. It must not be compared with a channel id.
|
||||
const incomingTargetId = rawTargetId && rawTargetId !== "0" ? rawTargetId : undefined;
|
||||
chatMessages.push({
|
||||
id: `remote-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
scope: incomingScope,
|
||||
...(incomingTargetId ? { targetId: incomingTargetId } : {}),
|
||||
...(incomingScope === "private" ? { conversationId: String(Number(msg.invokerId) || 0) } : {}),
|
||||
senderId: Number(msg.invokerId) || undefined,
|
||||
senderUid: typeof msg.senderUid === "string" ? msg.senderUid : undefined,
|
||||
invokerName: String(msg.invokerName || "Unknown"),
|
||||
message: String(msg.message || ""),
|
||||
timestamp: typeof msg.timestamp === "number" ? msg.timestamp : Date.now(),
|
||||
});
|
||||
break;
|
||||
case "serverEvent":
|
||||
if (msg.event && typeof msg.event.id === "string") serverEvents.push(msg.event as ServerEvent);
|
||||
break;
|
||||
case "pokeReceived":
|
||||
pokeNotifications.push({
|
||||
id: `poke-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
invokerId: Number(msg.invokerId) || 0,
|
||||
invokerUid: typeof msg.invokerUid === "string" ? msg.invokerUid : "",
|
||||
invokerName: String(msg.invokerName || "Unknown"),
|
||||
message: String(msg.message || ""),
|
||||
timestamp: typeof msg.timestamp === "number" ? msg.timestamp : Date.now(),
|
||||
});
|
||||
break;
|
||||
case "channelSwitched":
|
||||
state.channelSwitchedChannelId = typeof msg.channelId === "string" || typeof msg.channelId === "number" ? String(msg.channelId) : "";
|
||||
state.error = "";
|
||||
@@ -1263,34 +1200,44 @@ export function useVoiceWebSocket() {
|
||||
return audioDiagnostics.measure(timeoutMs);
|
||||
}
|
||||
|
||||
function sendTextMessage(message: string, targetId = ""): void {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed || trimmed.length > 500) return;
|
||||
sendCmd("sendTextMessage", { message: trimmed });
|
||||
chatMessages.push({
|
||||
id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
scope: "channel",
|
||||
...(targetId ? { targetId } : {}),
|
||||
senderId: state.tsClientId,
|
||||
invokerName: "你",
|
||||
message: trimmed,
|
||||
timestamp: Date.now(),
|
||||
isSelf: true,
|
||||
});
|
||||
function chatText(message: string): string {
|
||||
if (!state.connected || ws.value?.readyState !== WebSocket.OPEN) {
|
||||
throw Object.assign(new Error("TeamSpeak 会话尚未就绪"), { code: "SESSION_NOT_READY" });
|
||||
}
|
||||
const text = message.trim();
|
||||
if (!text || text.length > 500) throw Object.assign(new Error("文字消息无效"), { code: "INVALID_TEXT_MESSAGE" });
|
||||
return text;
|
||||
}
|
||||
|
||||
function sendServerMessage(message: string): void {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed || trimmed.length > 500) return;
|
||||
sendCmd("sendServerMessage", { message: trimmed });
|
||||
chatMessages.push({ id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, scope: "server", senderId: state.tsClientId, invokerName: "你", message: trimmed, timestamp: Date.now(), isSelf: true });
|
||||
async function sendChat<K extends "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage">(
|
||||
type: K, payload: ClientCommandPayloads[K], local: Pick<ChatMessage, "scope" | "targetId" | "conversationId" | "conversationKey" | "conversationName">,
|
||||
): Promise<void> {
|
||||
const generation = chatGeneration;
|
||||
const senderId = state.tsClientId;
|
||||
await sendCommandAndWait(type, payload);
|
||||
if (generation !== chatGeneration || !state.connected) throw new Error("语音连接已关闭");
|
||||
sessionState.appendLocal({ ...local, senderId, invokerName: "你", message: payload.message });
|
||||
}
|
||||
|
||||
function sendPrivateMessage(clientId: number, message: string, targetId = ""): void {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed || trimmed.length > 500) return;
|
||||
sendCmd("sendPrivateMessage", { clientId, message: trimmed });
|
||||
chatMessages.push({ id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, scope: "private", targetId, conversationId: String(clientId), senderId: state.tsClientId, invokerName: "你", message: trimmed, timestamp: Date.now(), isSelf: true });
|
||||
async function sendTextMessage(message: string, targetId = ""): Promise<void> {
|
||||
const text = chatText(message);
|
||||
await sendChat("sendTextMessage", { message: text, ...(targetId ? { channelId: targetId } : {}) },
|
||||
{ scope: "channel", ...(targetId ? { targetId } : {}) });
|
||||
}
|
||||
|
||||
async function sendServerMessage(message: string): Promise<void> {
|
||||
await sendChat("sendServerMessage", { message: chatText(message) }, { scope: "server" });
|
||||
}
|
||||
|
||||
async function sendPrivateMessage(clientId: number, message: string, targetId = "", expectedKey?: string): Promise<void> {
|
||||
const text = chatText(message);
|
||||
const member = members.find(candidate => candidate.id === clientId);
|
||||
const key = sessionState.memberConversationKey(clientId);
|
||||
if (!member || clientId === state.tsClientId || (expectedKey !== undefined && key !== expectedKey)) {
|
||||
throw Object.assign(new Error("成员已离线或当前不可见"), { code: "CLIENT_NOT_FOUND" });
|
||||
}
|
||||
await sendChat("sendPrivateMessage", { clientId, message: text, ...(member.uid ? { clientUid: member.uid } : {}) },
|
||||
{ scope: "private", targetId, conversationId: String(clientId), conversationKey: key, conversationName: member.nickname });
|
||||
}
|
||||
|
||||
function sendPoke(clientId: number, message = ""): void {
|
||||
@@ -1451,6 +1398,8 @@ export function useVoiceWebSocket() {
|
||||
...screenShare.api,
|
||||
ws,
|
||||
state,
|
||||
sessionEpoch: sessionState.epoch,
|
||||
memberConversationKey: sessionState.memberConversationKey,
|
||||
members,
|
||||
channels,
|
||||
chatMessages,
|
||||
|
||||
@@ -28,37 +28,27 @@ export function useWebClientChannels({
|
||||
t,
|
||||
}: UseWebClientChannelsOptions) {
|
||||
const channelTree = computed<TreeChannel[]>(() => {
|
||||
const source = [...channels];
|
||||
const unique = new Map<string, ChannelInfo>();
|
||||
for (const channel of channels) if (!unique.has(channel.id)) unique.set(channel.id, channel);
|
||||
const source = [...unique.values()];
|
||||
const sourceIndex = new Map(source.map((item, index) => [item.id, index]));
|
||||
const enriched = source.map((item) => ({
|
||||
...item,
|
||||
members: (item.members ?? []).map((member) => ({ ...member, isSelf: member.id === clientId.value })),
|
||||
}));
|
||||
const byId = new Map(enriched.map((item) => [item.id, item]));
|
||||
const depthCache = new Map<string, number>();
|
||||
|
||||
function depthOf(item: ChannelInfo, visiting = new Set<string>()): number {
|
||||
if (depthCache.has(item.id)) return depthCache.get(item.id)!;
|
||||
if (!item.parentID || item.parentID === "0" || visiting.has(item.id)) return 0;
|
||||
const parent = byId.get(item.parentID);
|
||||
const depth = parent ? depthOf(parent, new Set(visiting).add(item.id)) + 1 : 0;
|
||||
depthCache.set(item.id, depth);
|
||||
return depth;
|
||||
}
|
||||
|
||||
const childrenByParent = new Map<string, TreeChannel[]>();
|
||||
type ListedChannel = (typeof enriched)[number];
|
||||
const childrenByParent = new Map<string, ListedChannel[]>();
|
||||
for (const item of enriched) {
|
||||
const treeChannel = { ...item, depth: depthOf(item) };
|
||||
const siblings = childrenByParent.get(treeChannel.parentID) ?? [];
|
||||
siblings.push(treeChannel);
|
||||
childrenByParent.set(treeChannel.parentID, siblings);
|
||||
const siblings = childrenByParent.get(item.parentID) ?? [];
|
||||
siblings.push(item);
|
||||
childrenByParent.set(item.parentID, siblings);
|
||||
}
|
||||
|
||||
function orderSiblings(siblings: TreeChannel[]): TreeChannel[] {
|
||||
function orderSiblings(siblings: ListedChannel[]): ListedChannel[] {
|
||||
const bySiblingId = new Map(siblings.map((item) => [item.id, item]));
|
||||
const successors = new Map<string, TreeChannel[]>();
|
||||
const roots: TreeChannel[] = [];
|
||||
const sourceOrder = (left: TreeChannel, right: TreeChannel) =>
|
||||
const successors = new Map<string, ListedChannel[]>();
|
||||
const roots: ListedChannel[] = [];
|
||||
const sourceOrder = (left: ListedChannel, right: ListedChannel) =>
|
||||
(sourceIndex.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (sourceIndex.get(right.id) ?? Number.MAX_SAFE_INTEGER);
|
||||
|
||||
for (const item of siblings) {
|
||||
@@ -70,13 +60,18 @@ export function useWebClientChannels({
|
||||
roots.sort(sourceOrder);
|
||||
for (const items of successors.values()) items.sort(sourceOrder);
|
||||
|
||||
const ordered: TreeChannel[] = [];
|
||||
const ordered: ListedChannel[] = [];
|
||||
const visited = new Set<string>();
|
||||
const append = (item: TreeChannel) => {
|
||||
if (visited.has(item.id)) return;
|
||||
visited.add(item.id);
|
||||
ordered.push(item);
|
||||
for (const successor of successors.get(item.id) ?? []) append(successor);
|
||||
const append = (item: ListedChannel) => {
|
||||
const pending = [item];
|
||||
while (pending.length) {
|
||||
const next = pending.pop()!;
|
||||
if (visited.has(next.id)) continue;
|
||||
visited.add(next.id);
|
||||
ordered.push(next);
|
||||
const following = successors.get(next.id) ?? [];
|
||||
for (let index = following.length - 1; index >= 0; index--) pending.push(following[index]);
|
||||
}
|
||||
};
|
||||
for (const root of roots) append(root);
|
||||
for (const item of [...siblings].sort(sourceOrder)) append(item);
|
||||
@@ -84,18 +79,24 @@ export function useWebClientChannels({
|
||||
}
|
||||
|
||||
const orderedTree: TreeChannel[] = [];
|
||||
const visit = (parentID: string) => {
|
||||
for (const treeChannel of orderSiblings(childrenByParent.get(parentID) ?? [])) {
|
||||
orderedTree.push(treeChannel);
|
||||
visit(treeChannel.id);
|
||||
const visited = new Set<string>();
|
||||
const visit = (roots: ListedChannel[]) => {
|
||||
const pending = orderSiblings(roots).reverse().map(channel => ({ channel, depth: 0 }));
|
||||
while (pending.length) {
|
||||
const { channel, depth } = pending.pop()!;
|
||||
if (visited.has(channel.id)) continue;
|
||||
visited.add(channel.id);
|
||||
orderedTree.push({ ...channel, depth });
|
||||
const children = orderSiblings(childrenByParent.get(channel.id) ?? []);
|
||||
for (let index = children.length - 1; index >= 0; index--) pending.push({ channel: children[index], depth: depth + 1 });
|
||||
}
|
||||
};
|
||||
visit("0");
|
||||
visit(childrenByParent.get("0") ?? []);
|
||||
// Missing parents become roots; disconnected cycles start at their first
|
||||
// source entry. Both traversals are iterative and emit each ID at most once.
|
||||
visit(enriched.filter(channel => !unique.has(channel.parentID) && channel.parentID !== "0"));
|
||||
for (const item of enriched) {
|
||||
if (!orderedTree.some((treeChannel) => treeChannel.id === item.id)) {
|
||||
orderedTree.push({ ...item, depth: depthOf(item) });
|
||||
visit(item.id);
|
||||
}
|
||||
if (!visited.has(item.id)) visit([item]);
|
||||
}
|
||||
return orderedTree;
|
||||
});
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { computed, nextTick, ref, watch, type Ref } from "vue";
|
||||
import { computed, nextTick, onScopeDispose, ref, watch, type Ref } from "vue";
|
||||
import type { ChannelInfo, ChannelMember, ChatMessage } from "./useVoiceWebSocket.js";
|
||||
|
||||
export type WebClientChatTab = "channel" | "server" | "private" | "events";
|
||||
|
||||
interface PrivateConversation {
|
||||
id: number;
|
||||
key: string;
|
||||
name: string;
|
||||
lastMessage: number;
|
||||
}
|
||||
@@ -16,12 +17,15 @@ interface UseWebClientChatOptions {
|
||||
currentChannelName: Readonly<Ref<string>>;
|
||||
selectedChannelId: Ref<string>;
|
||||
clientId: Readonly<Ref<number>>;
|
||||
connected: Readonly<Ref<boolean>>;
|
||||
sessionEpoch: Readonly<Ref<number>>;
|
||||
memberConversationKey: (id: number) => string | undefined;
|
||||
isMobileViewport: Readonly<Ref<boolean>>;
|
||||
mobileSection: Ref<"channels" | "chat" | "voice" | "more">;
|
||||
closeMemberMenu: () => void;
|
||||
sendTextMessage: (text: string, targetId?: string) => void;
|
||||
sendServerMessage: (text: string) => void;
|
||||
sendPrivateMessage: (clientId: number, text: string, conversationId?: string) => void;
|
||||
sendTextMessage: (text: string, targetId?: string) => Promise<void>;
|
||||
sendServerMessage: (text: string) => Promise<void>;
|
||||
sendPrivateMessage: (clientId: number, text: string, conversationId?: string, expectedKey?: string) => Promise<void>;
|
||||
notifyPrivateMessage: () => void;
|
||||
t: (key: string, variables?: Record<string, string | number>) => string;
|
||||
}
|
||||
@@ -33,6 +37,9 @@ export function useWebClientChat({
|
||||
currentChannelName,
|
||||
selectedChannelId,
|
||||
clientId,
|
||||
connected,
|
||||
sessionEpoch,
|
||||
memberConversationKey,
|
||||
isMobileViewport,
|
||||
mobileSection,
|
||||
closeMemberMenu,
|
||||
@@ -44,8 +51,21 @@ export function useWebClientChat({
|
||||
}: UseWebClientChatOptions) {
|
||||
const tab = ref<WebClientChatTab>("channel");
|
||||
const privateClientId = ref(0);
|
||||
const privateConversationKey = ref("");
|
||||
const messageDraft = ref("");
|
||||
const listElement = ref<HTMLElement | null>(null);
|
||||
const sending = ref(false);
|
||||
const sendError = ref("");
|
||||
const drafts = new Map<string, string>();
|
||||
const pending = new Map<string, object>();
|
||||
const errors = new Map<string, string>();
|
||||
let disposed = false;
|
||||
const recipient = computed(() => members.find(member => member.id === privateClientId.value && memberConversationKey(member.id) === privateConversationKey.value));
|
||||
const destination = computed(() => `${sessionEpoch.value}:${tab.value}:${tab.value === "private" ? privateConversationKey.value : tab.value === "channel" ? currentChannel.value?.id ?? selectedChannelId.value : ""}`);
|
||||
const canSend = computed(() => connected.value && !sending.value && tab.value !== "events" && (tab.value !== "private" || Boolean(recipient.value)));
|
||||
const status = computed(() => sendError.value ? t(sendError.value) : sending.value ? t("chatSending")
|
||||
: !connected.value ? t("chatNotConnected") : tab.value === "private" && !recipient.value ? t("chatTargetUnavailable") : "");
|
||||
const messageKey = (message: ChatMessage) => message.conversationKey ?? `legacy:${message.id}`;
|
||||
|
||||
const conversations = computed<PrivateConversation[]>(() => {
|
||||
const byConversation = new Map<string, PrivateConversation>();
|
||||
@@ -53,11 +73,12 @@ export function useWebClientChat({
|
||||
if (message.scope !== "private" || !message.conversationId) continue;
|
||||
const id = Number(message.conversationId);
|
||||
if (!id) continue;
|
||||
const member = members.find((candidate) => candidate.id === id);
|
||||
const existing = byConversation.get(message.conversationId);
|
||||
byConversation.set(message.conversationId, {
|
||||
id,
|
||||
name: member?.nickname ?? existing?.name ?? message.invokerName,
|
||||
const key = messageKey(message);
|
||||
const member = members.find(candidate => memberConversationKey(candidate.id) === key);
|
||||
const existing = byConversation.get(key);
|
||||
byConversation.set(key, {
|
||||
id: member?.id ?? id, key,
|
||||
name: member?.nickname ?? message.conversationName ?? existing?.name ?? (message.isSelf ? t("privateMessage") : message.invokerName),
|
||||
lastMessage: Math.max(existing?.lastMessage ?? 0, message.timestamp),
|
||||
});
|
||||
}
|
||||
@@ -66,7 +87,7 @@ export function useWebClientChat({
|
||||
|
||||
const visibleMessages = computed(() => {
|
||||
if (tab.value === "server") return messages.filter((message) => message.scope === "server");
|
||||
if (tab.value === "private") return messages.filter((message) => message.scope === "private" && message.conversationId === String(privateClientId.value));
|
||||
if (tab.value === "private") return messages.filter(message => message.scope === "private" && messageKey(message) === privateConversationKey.value);
|
||||
if (tab.value !== "channel") return [];
|
||||
const channelId = currentChannel.value?.id;
|
||||
return messages.filter((message) => message.scope === "channel" && (!message.targetId || message.targetId === "0" || !channelId || message.targetId === channelId));
|
||||
@@ -79,31 +100,86 @@ export function useWebClientChat({
|
||||
? t("serverChat")
|
||||
: tab.value === "events"
|
||||
? t("eventLog")
|
||||
: conversations.value.find((conversation) => conversation.id === privateClientId.value)?.name ?? t("privateMessage"));
|
||||
: recipient.value?.nickname ?? conversations.value.find(conversation => conversation.key === privateConversationKey.value)?.name ?? t("privateMessage"));
|
||||
const placeholder = computed(() => tab.value === "private" ? t("privateMessagePlaceholder") : tab.value === "server" ? t("serverMessagePlaceholder") : t("sendMessagePlaceholder"));
|
||||
|
||||
function scrollToEnd(): void {
|
||||
const list = listElement.value;
|
||||
if (list) list.scrollTo({ top: list.scrollHeight, behavior: "smooth" });
|
||||
if (!disposed && list) list.scrollTo({ top: list.scrollHeight, behavior: "smooth" });
|
||||
}
|
||||
|
||||
function openPrivateChat(targetClientId: number): void {
|
||||
if (!targetClientId || targetClientId === clientId.value) return;
|
||||
privateClientId.value = targetClientId;
|
||||
const member = members.find(candidate => candidate.id === targetClientId);
|
||||
const key = memberConversationKey(targetClientId);
|
||||
if (!member || !key || targetClientId === clientId.value) return;
|
||||
openConversation({ id: targetClientId, key, name: member.nickname, lastMessage: 0 });
|
||||
}
|
||||
|
||||
function openConversation(conversation: PrivateConversation): void {
|
||||
if (disposed) return;
|
||||
privateClientId.value = conversation.id;
|
||||
privateConversationKey.value = conversation.key;
|
||||
tab.value = "private";
|
||||
if (isMobileViewport.value) mobileSection.value = "chat";
|
||||
closeMemberMenu();
|
||||
void nextTick(scrollToEnd);
|
||||
}
|
||||
|
||||
function submitMessage(): void {
|
||||
if (!messageDraft.value.trim()) return;
|
||||
if (tab.value === "channel") sendTextMessage(messageDraft.value, currentChannel.value?.id ?? selectedChannelId.value);
|
||||
else if (tab.value === "server") sendServerMessage(messageDraft.value);
|
||||
else if (tab.value === "private" && privateClientId.value) sendPrivateMessage(privateClientId.value, messageDraft.value, String(privateClientId.value));
|
||||
messageDraft.value = "";
|
||||
async function submitMessage(): Promise<void> {
|
||||
if (disposed || sending.value || !messageDraft.value.trim() || tab.value === "events") return;
|
||||
if (!connected.value) { sendError.value = "chatNotConnected"; return; }
|
||||
if (tab.value === "private" && !recipient.value) { sendError.value = "chatTargetUnavailable"; return; }
|
||||
const text = messageDraft.value;
|
||||
const key = destination.value;
|
||||
const operation = {};
|
||||
pending.set(key, operation);
|
||||
errors.delete(key);
|
||||
const isCurrent = () => !disposed && pending.get(key) === operation;
|
||||
sending.value = true;
|
||||
sendError.value = "";
|
||||
try {
|
||||
if (tab.value === "channel") await sendTextMessage(text, currentChannel.value?.id ?? selectedChannelId.value);
|
||||
else if (tab.value === "server") await sendServerMessage(text);
|
||||
else await sendPrivateMessage(privateClientId.value, text, String(privateClientId.value), privateConversationKey.value);
|
||||
if (isCurrent()) {
|
||||
if (destination.value === key && messageDraft.value === text) messageDraft.value = "";
|
||||
else if (drafts.get(key) === text) drafts.set(key, "");
|
||||
}
|
||||
} catch (error) {
|
||||
if (isCurrent()) {
|
||||
const code = (error as { code?: string } | null)?.code;
|
||||
const feedback = code === "CLIENT_NOT_FOUND" ? "chatTargetUnavailable" : code === "CHANNEL_CHANGED" ? "chatChannelChanged" : "chatSendFailed";
|
||||
errors.set(key, feedback);
|
||||
if (destination.value === key) sendError.value = feedback;
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent()) {
|
||||
pending.delete(key);
|
||||
if (destination.value === key) sending.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watch(destination, (next, previous) => {
|
||||
drafts.set(previous, messageDraft.value);
|
||||
messageDraft.value = drafts.get(next) ?? "";
|
||||
sending.value = pending.has(next);
|
||||
sendError.value = errors.get(next) ?? "";
|
||||
}, { flush: "sync" });
|
||||
watch(sessionEpoch, () => {
|
||||
drafts.clear();
|
||||
pending.clear();
|
||||
errors.clear();
|
||||
privateClientId.value = 0;
|
||||
privateConversationKey.value = "";
|
||||
tab.value = "channel";
|
||||
messageDraft.value = "";
|
||||
drafts.clear();
|
||||
sending.value = false;
|
||||
sendError.value = "";
|
||||
}, { flush: "sync" });
|
||||
onScopeDispose(() => { disposed = true; drafts.clear(); pending.clear(); errors.clear(); sending.value = false; });
|
||||
|
||||
watch([() => messages.length, tab, privateClientId], () => { void nextTick(scrollToEnd); });
|
||||
watch(() => messages.length, (length, previousLength) => {
|
||||
const latest = messages[length - 1];
|
||||
@@ -113,6 +189,8 @@ export function useWebClientChat({
|
||||
return {
|
||||
tab,
|
||||
privateClientId,
|
||||
privateConversationKey,
|
||||
sending, sendError, canSend, status,
|
||||
messageDraft,
|
||||
listElement,
|
||||
conversations,
|
||||
@@ -121,6 +199,7 @@ export function useWebClientChat({
|
||||
title,
|
||||
placeholder,
|
||||
openPrivateChat,
|
||||
openConversation,
|
||||
submitMessage,
|
||||
scrollToEnd,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user