获取全部用户
This commit is contained in:
@@ -49,7 +49,9 @@ export function updateWsStatus(connected) {
|
|||||||
export async function initWebSocket() {
|
export async function initWebSocket() {
|
||||||
try {
|
try {
|
||||||
await store.connectSignaling();
|
await store.connectSignaling();
|
||||||
|
store.syncSocketUserInfo();
|
||||||
updateWsStatus(true);
|
updateWsStatus(true);
|
||||||
|
await refreshOnlineUsers();
|
||||||
console.log('WebSocket initialized from connectview');
|
console.log('WebSocket initialized from connectview');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to initialize WebSocket:', error);
|
console.error('Failed to initialize WebSocket:', error);
|
||||||
@@ -58,11 +60,35 @@ export async function initWebSocket() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取全部在线WebSocket用户
|
||||||
|
* @param {boolean} silent - 是否静默刷新
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
if (!silent) {
|
||||||
|
showNotification(`当前共有 ${cachedOnlineUsers.length} 个WebSocket用户在线`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching online users:', error);
|
||||||
|
if (!silent) {
|
||||||
|
showNotification('获取在线用户失败', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取所有连接ID
|
* 获取所有连接ID
|
||||||
*/
|
*/
|
||||||
async function getAllConnectionIds() {
|
async function getAllConnectionIds() {
|
||||||
showNotification('正在获取连接ID列表...');
|
showNotification('正在获取连接ID和在线用户...');
|
||||||
try {
|
try {
|
||||||
const [connectionResponse, usersResponse] = await Promise.all([
|
const [connectionResponse, usersResponse] = await Promise.all([
|
||||||
fetch('/signaling/connection-ids'),
|
fetch('/signaling/connection-ids'),
|
||||||
@@ -136,11 +162,10 @@ function escapeHtml(value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按连接ID分组显示在线用户
|
* 显示全部在线WebSocket用户
|
||||||
* @param {Array} users - 在线用户列表
|
* @param {Array} users - 在线用户列表
|
||||||
* @param {string} selectedConnectionId - 当前选中的连接ID
|
|
||||||
*/
|
*/
|
||||||
function displayOnlineUsers(users, selectedConnectionId = '') {
|
function displayOnlineUsers(users) {
|
||||||
const onlineUsersList = document.getElementById('onlineUsersList');
|
const onlineUsersList = document.getElementById('onlineUsersList');
|
||||||
const usersContainer = document.getElementById('usersContainer');
|
const usersContainer = document.getElementById('usersContainer');
|
||||||
const onlineUsersSummary = document.getElementById('onlineUsersSummary');
|
const onlineUsersSummary = document.getElementById('onlineUsersSummary');
|
||||||
@@ -149,39 +174,33 @@ function displayOnlineUsers(users, selectedConnectionId = '') {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filteredUsers = selectedConnectionId
|
onlineUsersSummary.textContent = `${users.length} 个WebSocket用户在线`;
|
||||||
? users.filter(user => user.connectionId === selectedConnectionId)
|
|
||||||
: users;
|
|
||||||
|
|
||||||
onlineUsersSummary.textContent = selectedConnectionId
|
|
||||||
? `${filteredUsers.length} 人在线 · 房间 ${selectedConnectionId}`
|
|
||||||
: `${filteredUsers.length} 人在线`;
|
|
||||||
|
|
||||||
usersContainer.innerHTML = '';
|
usersContainer.innerHTML = '';
|
||||||
|
|
||||||
if (filteredUsers.length === 0) {
|
if (users.length === 0) {
|
||||||
usersContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无在线用户</p>';
|
usersContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无在线用户</p>';
|
||||||
onlineUsersList.classList.remove('hidden');
|
onlineUsersList.classList.remove('hidden');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupedUsers = filteredUsers.reduce((groups, user) => {
|
const groupedUsers = users.reduce((groups, user) => {
|
||||||
const connectionId = user.connectionId || 'unknown';
|
const groupName = user.connectionId ? `房间 ${user.connectionId}` : '大厅(未加入房间)';
|
||||||
if (!groups[connectionId]) {
|
if (!groups[groupName]) {
|
||||||
groups[connectionId] = [];
|
groups[groupName] = [];
|
||||||
}
|
}
|
||||||
groups[connectionId].push(user);
|
groups[groupName].push(user);
|
||||||
return groups;
|
return groups;
|
||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
Object.entries(groupedUsers).forEach(([connectionId, roomUsers]) => {
|
Object.entries(groupedUsers).forEach(([groupName, roomUsers]) => {
|
||||||
const section = document.createElement('div');
|
const section = document.createElement('div');
|
||||||
section.className = 'rounded-lg border border-white/10 bg-white/5 p-3';
|
section.className = 'rounded-lg border border-white/10 bg-white/5 p-3';
|
||||||
|
|
||||||
const roomTitle = document.createElement('div');
|
const roomTitle = document.createElement('div');
|
||||||
roomTitle.className = 'flex items-center justify-between mb-2';
|
roomTitle.className = 'flex items-center justify-between mb-2';
|
||||||
roomTitle.innerHTML = `
|
roomTitle.innerHTML = `
|
||||||
<span class="text-sm font-medium text-white">${escapeHtml(connectionId)}</span>
|
<span class="text-sm font-medium text-white">${escapeHtml(groupName)}</span>
|
||||||
<span class="text-xs text-gray-400">${roomUsers.length} 人</span>
|
<span class="text-xs text-gray-400">${roomUsers.length} 人</span>
|
||||||
`;
|
`;
|
||||||
section.appendChild(roomTitle);
|
section.appendChild(roomTitle);
|
||||||
@@ -192,7 +211,7 @@ function displayOnlineUsers(users, selectedConnectionId = '') {
|
|||||||
roomUsers.forEach((user) => {
|
roomUsers.forEach((user) => {
|
||||||
const userName = user.name || user.userId || '匿名用户';
|
const userName = user.name || user.userId || '匿名用户';
|
||||||
const avatar = user.avatar || '/images/p2.png';
|
const avatar = user.avatar || '/images/p2.png';
|
||||||
const roleLabel = user.role === 'host' ? '房主' : '成员';
|
const roleLabel = user.role === 'host' ? '房主' : (user.role === 'participant' ? '成员' : '大厅');
|
||||||
const userItem = document.createElement('div');
|
const userItem = document.createElement('div');
|
||||||
userItem.className = 'flex items-center justify-between rounded-lg bg-black/20 px-3 py-2';
|
userItem.className = 'flex items-center justify-between rounded-lg bg-black/20 px-3 py-2';
|
||||||
userItem.innerHTML = `
|
userItem.innerHTML = `
|
||||||
@@ -200,10 +219,10 @@ function displayOnlineUsers(users, selectedConnectionId = '') {
|
|||||||
<img src="${escapeHtml(avatar)}" alt="${escapeHtml(userName)}" class="w-8 h-8 rounded-full object-cover">
|
<img src="${escapeHtml(avatar)}" alt="${escapeHtml(userName)}" class="w-8 h-8 rounded-full object-cover">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-sm text-white truncate">${escapeHtml(userName)}</div>
|
<div class="text-sm text-white truncate">${escapeHtml(userName)}</div>
|
||||||
<div class="text-xs text-gray-400 truncate">${escapeHtml(user.userId || user.participantId || '未设置ID')}</div>
|
<div class="text-xs text-gray-400 truncate">${escapeHtml(user.userId || user.socketId || user.participantId || '未设置ID')}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<span class="text-xs px-2 py-1 rounded-full ${user.role === 'host' ? 'bg-indigo-500/20 text-indigo-300' : 'bg-white/10 text-gray-300'}">${roleLabel}</span>
|
<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>
|
||||||
`;
|
`;
|
||||||
roomList.appendChild(userItem);
|
roomList.appendChild(userItem);
|
||||||
});
|
});
|
||||||
@@ -223,7 +242,6 @@ function selectConnectionId(id) {
|
|||||||
const connectionIdInput = document.getElementById('connectionIdInput');
|
const connectionIdInput = document.getElementById('connectionIdInput');
|
||||||
if (connectionIdInput) {
|
if (connectionIdInput) {
|
||||||
connectionIdInput.value = id;
|
connectionIdInput.value = id;
|
||||||
displayOnlineUsers(cachedOnlineUsers, id);
|
|
||||||
showNotification(`已选择连接ID: ${id}`);
|
showNotification(`已选择连接ID: ${id}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,6 +325,7 @@ export function saveSettings() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
localStorage.setItem('userSettings', JSON.stringify(settings));
|
localStorage.setItem('userSettings', JSON.stringify(settings));
|
||||||
|
store.syncSocketUserInfo(settings);
|
||||||
|
|
||||||
if (userName) userName.textContent = settings.name;
|
if (userName) userName.textContent = settings.name;
|
||||||
if (userAvatar) userAvatar.src = settings.avatar;
|
if (userAvatar) userAvatar.src = settings.avatar;
|
||||||
|
|||||||
@@ -108,8 +108,8 @@
|
|||||||
|
|
||||||
<div id="onlineUsersList" class="glass rounded-xl p-4 mb-6 hidden">
|
<div id="onlineUsersList" class="glass rounded-xl p-4 mb-6 hidden">
|
||||||
<div class="flex items-center justify-between mb-2">
|
<div class="flex items-center justify-between mb-2">
|
||||||
<h3 class="text-sm font-medium text-gray-300">在线用户</h3>
|
<h3 class="text-sm font-medium text-gray-300">全部WebSocket用户</h3>
|
||||||
<span id="onlineUsersSummary" class="text-xs text-gray-500">0 人在线</span>
|
<span id="onlineUsersSummary" class="text-xs text-gray-500">0 个用户在线</span>
|
||||||
</div>
|
</div>
|
||||||
<div id="usersContainer" class="max-h-56 overflow-y-auto space-y-3">
|
<div id="usersContainer" class="max-h-56 overflow-y-auto space-y-3">
|
||||||
<!-- 在线用户将在这里动态生成 -->
|
<!-- 在线用户将在这里动态生成 -->
|
||||||
|
|||||||
@@ -343,6 +343,41 @@ class CallStateManager {
|
|||||||
return this._signaling;
|
return this._signaling;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在仅建立WebSocket连接时同步当前用户信息
|
||||||
|
* @param {{ id?: string, name?: string, avatar?: string } | null} userInfo - 用户信息
|
||||||
|
*/
|
||||||
|
syncSocketUserInfo(userInfo = null) {
|
||||||
|
const settings = userInfo || (() => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(localStorage.getItem('userSettings') || '{}');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error parsing user settings:', error);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
id: settings.id || settings.userId || this.state.session.localUser.id || '',
|
||||||
|
name: settings.name || this.state.session.localUser.name || '我',
|
||||||
|
avatar: settings.avatar || this.state.session.localUser.avatar || '/images/p1.png'
|
||||||
|
};
|
||||||
|
|
||||||
|
this.state.session.localUser = {
|
||||||
|
...this.state.session.localUser,
|
||||||
|
id: payload.id,
|
||||||
|
name: payload.name,
|
||||||
|
avatar: payload.avatar
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this._signaling && typeof this._signaling.sendMessage === 'function') {
|
||||||
|
this._signaling.sendMessage('', {
|
||||||
|
type: 'user-info',
|
||||||
|
data: payload
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建信令和RTC实例
|
* 创建信令和RTC实例
|
||||||
* @async
|
* @async
|
||||||
|
|||||||
@@ -1116,8 +1116,8 @@ function getAllConnectionIds(req: Request, res: Response): void {
|
|||||||
* @swagger
|
* @swagger
|
||||||
* /signaling/users:
|
* /signaling/users:
|
||||||
* get:
|
* get:
|
||||||
* summary: 获取在线WebSocket用户列表
|
* summary: 获取全部在线WebSocket用户列表
|
||||||
* description: 获取所有在线WebSocket用户,支持按 connectionId 过滤指定房间内的用户
|
* description: 获取所有当前已建立WebSocket连接的用户,包括未加入房间的大厅用户;支持按 connectionId 过滤指定房间内的用户
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: connectionId
|
* name: connectionId
|
||||||
@@ -1146,8 +1146,11 @@ function getAllConnectionIds(req: Request, res: Response): void {
|
|||||||
* description: 参与者ID
|
* description: 参与者ID
|
||||||
* role:
|
* role:
|
||||||
* type: string
|
* type: string
|
||||||
* enum: [host, participant]
|
* enum: [host, participant, idle]
|
||||||
* description: 角色
|
* description: 角色
|
||||||
|
* socketId:
|
||||||
|
* type: string
|
||||||
|
* description: WebSocket连接ID
|
||||||
* userId:
|
* userId:
|
||||||
* type: string
|
* type: string
|
||||||
* description: 用户ID
|
* description: 用户ID
|
||||||
@@ -1159,7 +1162,7 @@ function getAllConnectionIds(req: Request, res: Response): void {
|
|||||||
* description: 用户头像URL
|
* description: 用户头像URL
|
||||||
* totalCount:
|
* totalCount:
|
||||||
* type: number
|
* type: number
|
||||||
* description: 在线用户总数
|
* description: 在线WebSocket用户总数
|
||||||
*/
|
*/
|
||||||
function getOnlineUsers(req: Request, res: Response): void {
|
function getOnlineUsers(req: Request, res: Response): void {
|
||||||
const connectionId = typeof req.query.connectionId === 'string' ? req.query.connectionId : undefined;
|
const connectionId = typeof req.query.connectionId === 'string' ? req.query.connectionId : undefined;
|
||||||
|
|||||||
@@ -36,9 +36,10 @@ interface UserInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface OnlineUser {
|
interface OnlineUser {
|
||||||
|
socketId: string;
|
||||||
connectionId: string;
|
connectionId: string;
|
||||||
participantId: string;
|
participantId: string;
|
||||||
role: 'host' | 'participant';
|
role: 'host' | 'participant' | 'idle';
|
||||||
userId: string;
|
userId: string;
|
||||||
name: string;
|
name: string;
|
||||||
avatar: string;
|
avatar: string;
|
||||||
@@ -88,6 +89,7 @@ function add(ws: WebSocket): void {
|
|||||||
// 为新连接创建空的连接ID集合
|
// 为新连接创建空的连接ID集合
|
||||||
const id = new Set<string>();
|
const id = new Set<string>();
|
||||||
clients.set(ws, id);
|
clients.set(ws, id);
|
||||||
|
(ws as any).socketId = (ws as any).socketId || `ws_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||||
// 记录添加WebSocket连接的日志
|
// 记录添加WebSocket连接的日志
|
||||||
log(LogLevel.log, `Add WebSocket: ${ws.url}`);
|
log(LogLevel.log, `Add WebSocket: ${ws.url}`);
|
||||||
}
|
}
|
||||||
@@ -455,19 +457,38 @@ function onGetAllConnectionIds(): string[] {
|
|||||||
return connectionIds;
|
return connectionIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取WebSocket连接当前角色
|
||||||
|
* @param ws WebSocket连接实例
|
||||||
|
* @param connectionIds 该连接关联的connectionId集合
|
||||||
|
* @returns 用户角色
|
||||||
|
*/
|
||||||
|
function getSocketRole(ws: WebSocket, connectionIds: string[]): 'host' | 'participant' | 'idle' {
|
||||||
|
for (const connectionId of connectionIds) {
|
||||||
|
if (isHost(ws, connectionId)) {
|
||||||
|
return 'host';
|
||||||
|
}
|
||||||
|
const group = connectionGroup.get(connectionId);
|
||||||
|
if (group && group.participants.has(ws)) {
|
||||||
|
return 'participant';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'idle';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将WebSocket连接转换为在线用户信息
|
* 将WebSocket连接转换为在线用户信息
|
||||||
* @param ws WebSocket连接实例
|
* @param ws WebSocket连接实例
|
||||||
* @param connectionId 连接ID
|
|
||||||
* @param role 用户角色
|
|
||||||
* @returns 在线用户信息
|
* @returns 在线用户信息
|
||||||
*/
|
*/
|
||||||
function toOnlineUser(ws: WebSocket, connectionId: string, role: 'host' | 'participant'): OnlineUser {
|
function toOnlineUser(ws: WebSocket): OnlineUser {
|
||||||
|
const connectionIds = Array.from(clients.get(ws) || []);
|
||||||
const userInfo = ((ws as any).userInfo || {}) as UserInfo;
|
const userInfo = ((ws as any).userInfo || {}) as UserInfo;
|
||||||
return {
|
return {
|
||||||
connectionId: connectionId,
|
socketId: (ws as any).socketId || '',
|
||||||
|
connectionId: connectionIds[0] || '',
|
||||||
participantId: (ws as any).participantId || '',
|
participantId: (ws as any).participantId || '',
|
||||||
role: role,
|
role: getSocketRole(ws, connectionIds),
|
||||||
userId: userInfo.id || '',
|
userId: userInfo.id || '',
|
||||||
name: userInfo.name || '',
|
name: userInfo.name || '',
|
||||||
avatar: userInfo.avatar || ''
|
avatar: userInfo.avatar || ''
|
||||||
@@ -476,28 +497,17 @@ function toOnlineUser(ws: WebSocket, connectionId: string, role: 'host' | 'parti
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取在线WebSocket用户列表
|
* 获取在线WebSocket用户列表
|
||||||
* @param connectionId 可选的连接ID,传入时仅返回指定房间的在线用户
|
* @param connectionId 可选的连接ID,传入时仅返回关联该房间的在线用户
|
||||||
* @returns 在线用户列表
|
* @returns 在线用户列表
|
||||||
*/
|
*/
|
||||||
function onGetOnlineUsers(connectionId?: string): OnlineUser[] {
|
function onGetOnlineUsers(connectionId?: string): OnlineUser[] {
|
||||||
if (connectionId) {
|
|
||||||
const group = connectionGroup.get(connectionId);
|
|
||||||
if (!group) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
toOnlineUser(group.host, connectionId, 'host'),
|
|
||||||
...Array.from(group.participants).map((participantWs) => toOnlineUser(participantWs, connectionId, 'participant'))
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const onlineUsers: OnlineUser[] = [];
|
const onlineUsers: OnlineUser[] = [];
|
||||||
connectionGroup.forEach((group, currentConnectionId) => {
|
clients.forEach((connectionIds, ws) => {
|
||||||
onlineUsers.push(toOnlineUser(group.host, currentConnectionId, 'host'));
|
const ids = Array.from(connectionIds);
|
||||||
group.participants.forEach((participantWs) => {
|
if (connectionId && !ids.includes(connectionId)) {
|
||||||
onlineUsers.push(toOnlineUser(participantWs, currentConnectionId, 'participant'));
|
return;
|
||||||
});
|
}
|
||||||
|
onlineUsers.push(toOnlineUser(ws));
|
||||||
});
|
});
|
||||||
return onlineUsers;
|
return onlineUsers;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user