Files
webRtc/WebApp/client/public/onebyone/connect/connect.js

320 lines
10 KiB
JavaScript
Raw Normal View History

2026-03-04 18:40:19 +08:00
/**
* 连接界面逻辑
* 处理初始连接创建通话和加入通话的功能
*/
import store from '../store.js';
2026-03-04 21:44:17 +08:00
2026-03-04 18:40:19 +08:00
// 通知函数
function showNotification(message, type = 'info') {
const notification = document.getElementById('notification');
const notificationText = document.getElementById('notificationText');
if (notification && notificationText) {
notificationText.textContent = message;
// 清除之前的类
notification.className = 'fixed top-20 left-1/2 transform -translate-x-1/2 glass px-6 py-3 rounded-full flex items-center gap-3 opacity-0 pointer-events-none transition-all duration-300 z-50 translate-y-[-20px]';
// 根据类型添加不同的图标
const iconElement = notification.querySelector('i');
if (iconElement) {
iconElement.className = 'fas fa-info-circle text-indigo-400';
switch (type) {
case 'success':
iconElement.className = 'fas fa-check-circle text-green-400';
break;
case 'error':
iconElement.className = 'fas fa-exclamation-circle text-red-400';
break;
case 'warning':
iconElement.className = 'fas fa-exclamation-triangle text-yellow-400';
break;
}
}
// 显示通知
notification.classList.remove('opacity-0', 'translate-y-[-20px]');
notification.classList.add('opacity-100', 'translate-y-0');
// 3秒后隐藏
setTimeout(() => {
notification.classList.remove('opacity-100', 'translate-y-0');
notification.classList.add('opacity-0', 'translate-y-[-20px]');
}, 3000);
}
}
// 加入通话
function joinCall() {
const connectionId = document.getElementById('connectionIdInput').value.trim();
if (connectionId) {
showNotification(`正在加入通话 (${connectionId})`);
// 保存连接ID到本地存储
localStorage.setItem('connectionId', connectionId);
// 跳转到通话界面
window.location.href = '../index.html';
} else {
showNotification('请输入连接ID', 'error');
}
}
// 创建通话
function createCall() {
showNotification('正在创建通话...');
// 生成随机连接ID
const connectionId = 'conn_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
// 保存连接ID到本地存储
localStorage.setItem('connectionId', connectionId);
// 跳转到通话界面
window.location.href = '../index.html';
}
2026-03-04 21:44:17 +08:00
// 获取所有连接ID
async function getAllConnectionIds() {
showNotification('正在获取连接ID列表...');
try {
const response = await fetch('/signaling/connection-ids');
if (!response.ok) {
throw new Error('Failed to fetch connection IDs');
}
const data = await response.json();
displayConnectionIds(data.connectionIds);
} catch (error) {
console.error('Error fetching connection IDs:', error);
showNotification('获取连接ID失败', 'error');
}
}
// 显示连接ID列表
function displayConnectionIds(connectionIds) {
const idsContainer = document.getElementById('idsContainer');
const connectionIdsList = document.getElementById('connectionIdsList');
if (idsContainer) {
// 清空容器
idsContainer.innerHTML = '';
if (connectionIds.length === 0) {
idsContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无可用的连接ID</p>';
} else {
// 为每个连接ID创建一个元素
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);
});
}
// 显示连接ID列表
if (connectionIdsList) {
connectionIdsList.classList.remove('hidden');
}
showNotification(`找到 ${connectionIds.length} 个连接ID`);
}
}
// 选择连接ID
function selectConnectionId(id) {
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) {
connectionIdInput.value = id;
showNotification(`已选择连接ID: ${id}`);
}
}
2026-03-04 18:40:19 +08:00
// 绑定事件监听器
function bindEvents() {
// 连接按钮
const connectBtn = document.getElementById('connectBtn');
if (connectBtn) {
connectBtn.addEventListener('click', joinCall);
}
// 创建通话按钮
const createCallBtn = document.getElementById('createCallBtn');
if (createCallBtn) {
createCallBtn.addEventListener('click', createCall);
}
2026-03-04 21:44:17 +08:00
// 浏览全部ID按钮
const browseIdsBtn = document.getElementById('browseIdsBtn');
if (browseIdsBtn) {
browseIdsBtn.addEventListener('click', getAllConnectionIds);
}
2026-03-04 18:40:19 +08:00
// 输入框回车事件
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) {
connectionIdInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
joinCall();
}
});
}
}
2026-04-10 17:14:31 +08:00
// 生成8位的用户ID
function generateUserId() {
// 生成8位随机字符串包含字母和数字
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = 'user_';
for (let i = 0; i < 8; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
// 加载用户设置
function loadUserSettings() {
const userSettings = localStorage.getItem('userSettings');
if (userSettings) {
try {
const settings = JSON.parse(userSettings);
// 设置用户ID
if (settings.userId) {
document.getElementById('userIdInput').value = settings.userId;
}
// 设置昵称
if (settings.name) {
document.getElementById('nicknameInput').value = settings.name;
document.getElementById('userName').textContent = settings.name;
}
// 设置头像
if (settings.avatar) {
document.getElementById('userAvatar').src = settings.avatar;
document.getElementById('avatarPreview').src = settings.avatar;
}
} catch (error) {
console.error('Error loading user settings:', error);
}
} else {
// 生成新的用户ID
const newUserId = generateUserId();
document.getElementById('userIdInput').value = newUserId;
// 保存默认设置
saveSettings();
}
}
// 保存用户设置
function saveSettings() {
const settings = {
userId: document.getElementById('userIdInput').value,
name: document.getElementById('nicknameInput').value || '我',
avatar: document.getElementById('avatarPreview').src
};
localStorage.setItem('userSettings', JSON.stringify(settings));
// 更新界面显示
document.getElementById('userName').textContent = settings.name;
document.getElementById('userAvatar').src = settings.avatar;
showNotification('设置已保存', 'success');
}
// 处理头像上传
function handleAvatarUpload(event) {
const file = event.target.files[0];
if (file) {
// 检查文件类型
if (!file.type.startsWith('image/')) {
showNotification('请选择图片文件', 'error');
return;
}
// 检查文件大小
if (file.size > 2 * 1024 * 1024) { // 2MB限制
showNotification('图片大小不能超过2MB', 'error');
return;
}
// 读取图片文件
const reader = new FileReader();
reader.onload = function(e) {
const imageUrl = e.target.result;
document.getElementById('avatarPreview').src = imageUrl;
showNotification('头像已更新', 'success');
};
reader.readAsDataURL(file);
}
}
// 复制用户ID到剪贴板
function copyUserId() {
const userIdInput = document.getElementById('userIdInput');
userIdInput.select();
document.execCommand('copy');
showNotification('用户ID已复制到剪贴板', 'success');
}
// 切换设置菜单
function toggleSettingsMenu() {
const settingsMenu = document.getElementById('settingsMenu');
settingsMenu.classList.toggle('hidden');
}
// 点击外部关闭设置菜单
document.addEventListener('click', function(event) {
const settingsMenu = document.getElementById('settingsMenu');
const userSettingsBtn = document.getElementById('userSettingsBtn');
if (!settingsMenu.contains(event.target) && !userSettingsBtn.contains(event.target)) {
settingsMenu.classList.add('hidden');
}
});
// 绑定用户设置相关事件
function bindUserSettingsEvents() {
// 设置按钮点击事件
const userSettingsBtn = document.getElementById('userSettingsBtn');
if (userSettingsBtn) {
userSettingsBtn.addEventListener('click', toggleSettingsMenu);
}
}
2026-03-04 18:40:19 +08:00
// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
bindEvents();
2026-04-10 17:14:31 +08:00
bindUserSettingsEvents();
2026-03-04 18:40:19 +08:00
// 检查本地存储中是否有连接ID
const savedConnectionId = localStorage.getItem('connectionId');
if (savedConnectionId) {
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) {
connectionIdInput.value = savedConnectionId;
}
}
2026-04-10 17:14:31 +08:00
// 加载用户设置
loadUserSettings();
2026-03-04 18:40:19 +08:00
});
// 导出全局函数
window.showNotification = showNotification;
window.joinCall = joinCall;
window.createCall = createCall;
2026-03-04 21:44:17 +08:00
window.selectConnectionId = selectConnectionId;
2026-04-10 17:14:31 +08:00
window.saveSettings = saveSettings;
window.handleAvatarUpload = handleAvatarUpload;
window.copyUserId = copyUserId;
window.toggleSettingsMenu = toggleSettingsMenu;