通话模块拆分

This commit is contained in:
2026-05-24 12:43:16 +08:00
parent 554bb5d9ee
commit 9c05c6a9d9
4 changed files with 395 additions and 299 deletions

View File

@@ -5,6 +5,12 @@
import { showNotification } from './utils.js';
import store from './store.js';
import {
fetchConnectionDirectory,
fetchOnlineUsers,
renderConnectionIds,
renderOnlineUsers
} from './connect-directory.js';
const MAX_AVATAR_SIZE = 2 * 1024 * 1024; // 2MB
@@ -66,13 +72,8 @@ export async function initWebSocket() {
*/
async function refreshOnlineUsers(silent = true) {
try {
const response = await fetch('/signaling/users');
if (!response.ok) {
throw new Error('Failed to fetch online users');
}
const data = await response.json();
cachedOnlineUsers = Array.isArray(data.users) ? data.users : [];
displayOnlineUsers(cachedOnlineUsers);
cachedOnlineUsers = await fetchOnlineUsers();
updateOnlineUsersList(cachedOnlineUsers);
if (!silent) {
showNotification(`当前共有 ${cachedOnlineUsers.length} 个WebSocket用户在线`);
}
@@ -90,24 +91,10 @@ async function refreshOnlineUsers(silent = true) {
async function getAllConnectionIds() {
showNotification('正在获取连接ID和在线用户...');
try {
const [connectionResponse, usersResponse] = await Promise.all([
fetch('/signaling/connection-ids'),
fetch('/signaling/users')
]);
if (!connectionResponse.ok) {
throw new Error('Failed to fetch connection IDs');
}
if (!usersResponse.ok) {
throw new Error('Failed to fetch online users');
}
const connectionData = await connectionResponse.json();
const usersData = await usersResponse.json();
cachedOnlineUsers = Array.isArray(usersData.users) ? usersData.users : [];
displayConnectionIds(connectionData.connectionIds || []);
displayOnlineUsers(cachedOnlineUsers);
const { connectionIds, users } = await fetchConnectionDirectory();
cachedOnlineUsers = users;
updateConnectionIdList(connectionIds);
updateOnlineUsersList(cachedOnlineUsers);
} catch (error) {
console.error('Error fetching connection IDs:', error);
showNotification('获取连接信息失败', 'error');
@@ -118,49 +105,22 @@ async function getAllConnectionIds() {
* 显示连接ID列表
* @param {string[]} connectionIds - 连接ID数组
*/
function displayConnectionIds(connectionIds) {
function updateConnectionIdList(connectionIds) {
const idsContainer = document.getElementById('idsContainer');
const connectionIdsList = document.getElementById('connectionIdsList');
renderConnectionIds({
connectionIds,
idsContainer,
connectionIdsList,
onSelectConnectionId: selectConnectionId
});
if (idsContainer) {
idsContainer.innerHTML = '';
if (connectionIds.length === 0) {
idsContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无可用的连接ID</p>';
} else {
connectionIds.forEach(id => {
const idElement = document.createElement('div');
idElement.className = 'flex items-center justify-between p-2 bg-white/5 rounded-lg hover:bg-white/10 cursor-pointer transition-colors';
idElement.innerHTML = `
<span class="text-sm">${id}</span>
<button class="text-xs bg-indigo-600 hover:bg-indigo-700 px-2 py-1 rounded" onclick="selectConnectionId('${id}')">选择</button>
`;
idsContainer.appendChild(idElement);
});
}
if (connectionIdsList) {
connectionIdsList.classList.remove('hidden');
}
showNotification(`找到 ${connectionIds.length} 个连接ID`);
}
}
/**
* 转义HTML特殊字符
* @param {string} value - 原始字符串
* @returns {string} 安全字符串
*/
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function getCurrentUserId() {
try {
const settings = JSON.parse(localStorage.getItem('userSettings') || '{}');
@@ -175,77 +135,18 @@ function getCurrentUserId() {
* 显示全部在线WebSocket用户
* @param {Array} users - 在线用户列表
*/
function displayOnlineUsers(users) {
function updateOnlineUsersList(users) {
const onlineUsersList = document.getElementById('onlineUsersList');
const usersContainer = document.getElementById('usersContainer');
const onlineUsersSummary = document.getElementById('onlineUsersSummary');
if (!onlineUsersList || !usersContainer || !onlineUsersSummary) {
return;
}
onlineUsersSummary.textContent = `${users.length} 个WebSocket用户在线`;
usersContainer.innerHTML = '';
if (users.length === 0) {
usersContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无在线用户</p>';
onlineUsersList.classList.remove('hidden');
return;
}
const groupedUsers = users.reduce((groups, user) => {
const groupName = user.connectionId ? `房间 ${user.connectionId}` : '大厅(未加入房间)';
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(user);
return groups;
}, {});
Object.entries(groupedUsers).forEach(([groupName, roomUsers]) => {
const section = document.createElement('div');
section.className = 'rounded-lg border border-white/10 bg-white/5 p-3';
const roomTitle = document.createElement('div');
roomTitle.className = 'flex items-center justify-between mb-2';
roomTitle.innerHTML = `
<span class="text-sm font-medium text-white">${escapeHtml(groupName)}</span>
<span class="text-xs text-gray-400">${roomUsers.length} 人</span>
`;
section.appendChild(roomTitle);
const roomList = document.createElement('div');
roomList.className = 'space-y-2';
roomUsers.forEach((user) => {
const userName = user.name || user.userId || '匿名用户';
const avatar = user.avatar || '/images/p2.png';
const roleLabel = user.role === 'host' ? '房主' : (user.role === 'participant' ? '成员' : '大厅');
const isSelf = Boolean(user.userId) && user.userId === getCurrentUserId();
const userItem = document.createElement('div');
userItem.className = 'flex items-center justify-between rounded-lg bg-black/20 px-3 py-2';
userItem.innerHTML = `
<div class="flex items-center gap-3 min-w-0">
<img src="${escapeHtml(avatar)}" alt="${escapeHtml(userName)}" class="w-8 h-8 rounded-full object-cover">
<div class="min-w-0">
<div class="text-sm text-white truncate">${escapeHtml(userName)}</div>
<div class="text-xs text-gray-400 truncate">${escapeHtml(user.userId || user.socketId || user.participantId || '未设置ID')}</div>
</div>
</div>
<div class="flex items-center gap-2">
<span class="text-xs px-2 py-1 rounded-full ${user.role === 'host' ? 'bg-indigo-500/20 text-indigo-300' : (user.role === 'participant' ? 'bg-white/10 text-gray-300' : 'bg-emerald-500/20 text-emerald-300')}">${roleLabel}</span>
${isSelf ? '<span class="text-xs text-gray-500">自己</span>' : ''}
</div>
`;
roomList.appendChild(userItem);
});
section.appendChild(roomList);
usersContainer.appendChild(section);
renderOnlineUsers({
users,
currentUserId: getCurrentUserId(),
onlineUsersList,
usersContainer,
onlineUsersSummary
});
onlineUsersList.classList.remove('hidden');
}
/**