This commit is contained in:
theliu
2026-04-26 20:05:33 +08:00
commit 5ff0c575a1
21 changed files with 2507 additions and 0 deletions
+844
View File
@@ -0,0 +1,844 @@
/* 苹果风格深色主题 */
:root {
--bg-primary: #1c1c1e;
--bg-secondary: #2c2c2e;
--bg-tertiary: #3a3a3c;
--text-primary: #ffffff;
--text-secondary: #98989d;
--text-tertiary: #6c6c70;
--accent-blue: #0a84ff;
--accent-green: #30d158;
--accent-red: #ff453a;
--accent-orange: #ff9f0a;
--border-color: #38383a;
--shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
--radius-sm: 10px;
--radius-md: 14px;
--radius-lg: 20px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
body.dark-theme {
background-color: var(--bg-primary);
color: var(--text-primary);
height: 100vh;
overflow: hidden;
}
.app-container {
display: flex;
height: 100vh;
max-width: 1400px;
margin: 0 auto;
}
/* 侧边栏样式 */
.sidebar {
width: 320px;
background-color: var(--bg-secondary);
border-right: 1px solid var(--border-color);
display: flex;
flex-direction: column;
overflow: hidden;
}
.user-info {
display: flex;
align-items: center;
padding: 20px;
border-bottom: 1px solid var(--border-color);
}
.avatar {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: var(--bg-tertiary);
display: flex;
align-items: center;
justify-content: center;
margin-right: 12px;
font-size: 28px;
color: var(--text-secondary);
}
.user-details h3 {
font-size: 18px;
font-weight: 600;
margin-bottom: 4px;
}
.user-details p {
font-size: 14px;
color: var(--text-secondary);
}
.search-box {
padding: 16px 20px;
position: relative;
}
.search-box input {
width: 100%;
padding: 10px 40px;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-primary);
font-size: 14px;
}
.search-box i {
position: absolute;
left: 36px;
top: 50%;
transform: translateY(-50%);
color: var(--text-tertiary);
z-index: 1;
}
.nav-tabs {
display: flex;
padding: 0 20px;
margin-bottom: 10px;
}
.nav-btn {
flex: 1;
padding: 12px 0;
background: none;
border: none;
color: var(--text-secondary);
font-size: 14px;
cursor: pointer;
border-radius: var(--radius-sm);
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.nav-btn.active {
background-color: var(--bg-tertiary);
color: var(--text-primary);
}
.nav-btn:hover {
background-color: var(--bg-tertiary);
}
.chat-list {
flex: 1;
overflow-y: auto;
padding: 0 10px;
}
.chat-item {
display: flex;
align-items: center;
padding: 12px 16px;
border-radius: var(--radius-md);
cursor: pointer;
transition: background-color 0.2s;
margin-bottom: 4px;
}
.chat-item:hover {
background-color: var(--bg-tertiary);
}
.chat-item.active {
background-color: rgba(10, 132, 255, 0.1);
}
.chat-item-avatar {
width: 44px;
height: 44px;
border-radius: 50%;
background-color: var(--bg-tertiary);
display: flex;
align-items: center;
justify-content: center;
margin-right: 12px;
font-size: 22px;
color: var(--text-secondary);
}
.chat-item-info {
flex: 1;
min-width: 0;
}
.chat-item-name {
font-size: 16px;
font-weight: 500;
margin-bottom: 2px;
display: flex;
justify-content: space-between;
}
.chat-item-last-message {
font-size: 14px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.chat-item-time {
font-size: 12px;
color: var(--text-tertiary);
}
.chat-item-unread {
background-color: var(--accent-blue);
color: white;
font-size: 12px;
padding: 2px 8px;
border-radius: 10px;
margin-left: 8px;
}
/* 主聊天区域 */
.main-chat {
flex: 1;
display: flex;
flex-direction: column;
background-color: var(--bg-primary);
position: relative;
overflow: hidden;
}
.chat-header {
padding: 16px 24px;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--bg-secondary);
z-index: 10;
}
.chat-partner {
display: flex;
align-items: center;
}
.partner-avatar {
width: 44px;
height: 44px;
border-radius: 50%;
background-color: var(--bg-tertiary);
display: flex;
align-items: center;
justify-content: center;
margin-right: 12px;
font-size: 24px;
color: var(--text-secondary);
}
.partner-info h3 {
font-size: 18px;
font-weight: 600;
margin-bottom: 2px;
}
.partner-info p {
font-size: 14px;
color: var(--text-secondary);
}
.chat-actions {
display: flex;
gap: 12px;
}
.action-btn {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: var(--bg-tertiary);
border: none;
color: var(--text-primary);
font-size: 18px;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.action-btn:hover {
background-color: var(--accent-blue);
}
.action-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
}
.message {
display: flex;
max-width: 70%;
}
.message.received {
align-self: flex-start;
}
.message.sent {
align-self: flex-end;
flex-direction: row-reverse;
}
.message-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background-color: var(--bg-tertiary);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: var(--text-secondary);
margin-top: 4px;
}
.message.received .message-avatar {
margin-right: 12px;
}
.message.sent .message-avatar {
margin-left: 12px;
}
.message-content {
background-color: var(--bg-secondary);
padding: 12px 16px;
border-radius: var(--radius-lg);
position: relative;
}
.message.sent .message-content {
background-color: var(--accent-blue);
color: white;
border-bottom-right-radius: var(--radius-sm);
}
.message.received .message-content {
border-bottom-left-radius: var(--radius-sm);
}
.message-text {
font-size: 15px;
line-height: 1.4;
}
.message-time {
font-size: 12px;
color: var(--text-tertiary);
margin-top: 4px;
text-align: right;
}
.message.sent .message-time {
color: rgba(255, 255, 255, 0.8);
}
.chat-input-area {
padding: 20px 24px;
border-top: 1px solid var(--border-color);
background-color: var(--bg-secondary);
}
.input-tools {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
.tool-btn {
width: 36px;
height: 36px;
border-radius: 50%;
background: none;
border: 1px solid var(--border-color);
color: var(--text-primary);
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
.tool-btn:hover {
background-color: var(--bg-tertiary);
}
.message-input-wrapper {
display: flex;
gap: 12px;
align-items: flex-end;
}
.message-input-wrapper textarea {
flex: 1;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-primary);
padding: 12px 16px;
font-size: 15px;
resize: none;
max-height: 120px;
min-height: 44px;
line-height: 1.4;
}
.message-input-wrapper textarea:focus {
outline: none;
border-color: var(--accent-blue);
}
.send-btn {
width: 44px;
height: 44px;
border-radius: 50%;
background-color: var(--accent-blue);
border: none;
color: white;
font-size: 18px;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.send-btn:hover {
background-color: #007aff;
}
/* 语音通话界面 */
.call-interface {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
}
.call-container {
text-align: center;
max-width: 400px;
padding: 40px;
}
.call-avatar {
width: 120px;
height: 120px;
border-radius: 50%;
background-color: var(--bg-tertiary);
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 24px;
font-size: 60px;
color: var(--text-secondary);
}
.call-container h3 {
font-size: 24px;
margin-bottom: 8px;
}
.call-status {
font-size: 16px;
color: var(--text-secondary);
margin-bottom: 24px;
}
.call-timer {
font-size: 32px;
font-weight: 600;
margin: 24px 0;
color: var(--accent-green);
}
.call-controls {
display: flex;
justify-content: center;
gap: 40px;
margin-top: 40px;
}
.call-control-btn {
width: 64px;
height: 64px;
border-radius: 50%;
border: none;
font-size: 24px;
cursor: pointer;
transition: transform 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.call-control-btn:hover {
transform: scale(1.1);
}
.call-control-btn.decline {
background-color: var(--accent-red);
color: white;
}
.call-control-btn.accept {
background-color: var(--accent-green);
color: white;
}
/* 侧边栏 */
.contacts-sidebar,
.files-sidebar {
width: 320px;
background-color: var(--bg-secondary);
border-left: 1px solid var(--border-color);
display: flex;
flex-direction: column;
position: fixed;
top: 0;
right: -320px;
bottom: 0;
transition: right 0.3s;
z-index: 100;
}
.contacts-sidebar.active,
.files-sidebar.active {
right: 0;
}
.sidebar-header {
padding: 20px;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
}
.sidebar-header h3 {
font-size: 20px;
font-weight: 600;
}
.close-sidebar {
width: 36px;
height: 36px;
border-radius: 50%;
background: none;
border: none;
color: var(--text-primary);
font-size: 18px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.close-sidebar:hover {
background-color: var(--bg-tertiary);
}
.contacts-list,
.files-list {
flex: 1;
overflow-y: auto;
padding: 20px;
}
.contact-item {
display: flex;
align-items: center;
padding: 12px 16px;
border-radius: var(--radius-md);
cursor: pointer;
transition: background-color 0.2s;
margin-bottom: 8px;
}
.contact-item:hover {
background-color: var(--bg-tertiary);
}
.contact-status {
width: 8px;
height: 8px;
border-radius: 50%;
margin-left: auto;
}
.contact-status.online {
background-color: var(--accent-green);
}
.contact-status.offline {
background-color: var(--text-tertiary);
}
/* 移动端样式:显示顶部的联系人按钮并调整布局 */
@media (max-width: 768px) {
.sidebar { display: none; }
.action-btn#openContactsBtn { display: flex; }
.main-chat { padding-top: 0; }
.app-container { max-width: 100%; }
}
/* 文件上传模态框 */
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: none;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal.active {
display: flex;
}
.modal-content {
background-color: var(--bg-secondary);
border-radius: var(--radius-lg);
width: 90%;
max-width: 500px;
max-height: 90vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.modal-header {
padding: 20px 24px;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
}
.modal-header h3 {
font-size: 20px;
font-weight: 600;
}
.close-modal {
width: 36px;
height: 36px;
border-radius: 50%;
background: none;
border: none;
color: var(--text-primary);
font-size: 18px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.close-modal:hover {
background-color: var(--bg-tertiary);
}
.modal-body {
padding: 24px;
flex: 1;
overflow-y: auto;
}
.upload-area {
border: 2px dashed var(--border-color);
border-radius: var(--radius-md);
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: border-color 0.2s;
margin-bottom: 24px;
}
.upload-area:hover {
border-color: var(--accent-blue);
}
.upload-area i {
font-size: 48px;
color: var(--text-secondary);
margin-bottom: 16px;
}
.upload-area p {
font-size: 16px;
margin-bottom: 8px;
}
.upload-hint {
font-size: 14px;
color: var(--text-tertiary);
margin-bottom: 20px;
}
.upload-btn {
background-color: var(--accent-blue);
color: white;
border: none;
padding: 10px 24px;
border-radius: var(--radius-md);
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
.upload-btn:hover {
background-color: #007aff;
}
.file-preview {
margin-top: 20px;
}
.file-item {
display: flex;
align-items: center;
padding: 12px;
background-color: var(--bg-tertiary);
border-radius: var(--radius-md);
margin-bottom: 8px;
}
.file-icon {
width: 40px;
height: 40px;
background-color: var(--accent-blue);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 12px;
color: white;
}
.file-info {
flex: 1;
}
.file-name {
font-size: 14px;
font-weight: 500;
margin-bottom: 2px;
}
.file-size {
font-size: 12px;
color: var(--text-secondary);
}
/* 欢迎消息 */
.welcome-message {
text-align: center;
padding: 60px 20px;
color: var(--text-secondary);
}
.welcome-message i {
font-size: 64px;
margin-bottom: 24px;
opacity: 0.5;
}
.welcome-message h3 {
font-size: 24px;
margin-bottom: 12px;
color: var(--text-primary);
}
.welcome-message p {
font-size: 16px;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--text-tertiary);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}
/* 响应式设计 */
@media (max-width: 768px) {
.sidebar {
width: 100%;
position: fixed;
top: 0;
left: -100%;
bottom: 0;
transition: left 0.3s;
z-index: 100;
}
.sidebar.active {
left: 0;
}
.contacts-sidebar,
.files-sidebar {
width: 100%;
right: -100%;
}
.contacts-sidebar.active,
.files-sidebar.active {
right: 0;
}
.app-container {
flex-direction: column;
}
.message {
max-width: 85%;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

+851
View File
@@ -0,0 +1,851 @@
class WebWeChat {
constructor() {
this.socket = null;
this.currentUser = null;
self.currentContact = null;
this.contacts = [];
this.activeCall = null;
this.callTimer = null;
this.callStartTime = null;
this.peerConnection = null;
this.localStream = null;
this.init();
}
init() {
this.initSocket();
this.bindEvents();
this.loadContacts();
this.setupWebRTC();
// 如果是移动设备(窄屏),默认打开联系人侧栏以便选择对话
if (window.innerWidth <= 768) {
this.showContactsSidebar();
}
}
initSocket() {
// 连接WebSocket服务器
this.socket = io({
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionAttempts: 5
});
// Socket事件监听
this.socket.on('connect', () => {
console.log('WebSocket连接成功');
this.authenticate();
});
this.socket.on('disconnect', () => {
console.log('WebSocket断开连接');
});
this.socket.on('user_status', (data) => {
this.updateUserStatus(data.account, data.online);
});
this.socket.on('private_message', (data) => {
this.receiveMessage(data);
});
this.socket.on('private_message_sent', (data) => {
console.log('消息已发送:', data);
});
this.socket.on('incoming_call', (data) => {
this.handleIncomingCall(data);
});
this.socket.on('call_accepted', (data) => {
this.handleCallAccepted(data);
});
this.socket.on('call_ended', (data) => {
this.handleCallEnded(data);
});
this.socket.on('webrtc_signal', (signal) => {
this.handleWebRTCSignal(signal);
});
this.socket.on('file_received', (data) => {
this.showFileNotification(data);
});
}
authenticate() {
// 从localStorage获取用户信息
const account = localStorage.getItem('user_account');
if (account) {
this.socket.emit('authenticate', { account: account });
this.currentUser = account;
}
}
bindEvents() {
// 发送消息
document.getElementById('sendBtn').addEventListener('click', () => {
this.sendMessage();
});
document.getElementById('messageInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});
// 语音通话
document.getElementById('voiceCallBtn').addEventListener('click', () => {
this.startVoiceCall();
});
document.getElementById('endCallBtn').addEventListener('click', () => {
this.endCall();
});
document.getElementById('answerCallBtn').addEventListener('click', () => {
this.answerCall();
});
// 文件上传
document.getElementById('fileUploadBtn').addEventListener('click', () => {
this.showFileUploadModal();
});
document.getElementById('selectFileBtn').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', (e) => {
this.handleFileSelect(e.target.files[0]);
});
// 联系人列表
document.querySelectorAll('[data-tab="contacts"]').forEach(btn => {
btn.addEventListener('click', () => {
this.showContactsSidebar();
});
});
document.getElementById('closeContactsBtn').addEventListener('click', () => {
this.hideContactsSidebar();
});
// 手机端顶部打开联系人按钮
const openContactsBtn = document.getElementById('openContactsBtn');
if (openContactsBtn) {
openContactsBtn.addEventListener('click', () => {
this.showContactsSidebar();
});
}
// 文件列表
document.querySelectorAll('[data-tab="files"]').forEach(btn => {
btn.addEventListener('click', () => {
this.showFilesSidebar();
});
});
document.getElementById('closeFilesBtn').addEventListener('click', () => {
this.hideFilesSidebar();
});
// 关闭文件上传模态框
document.getElementById('closeFileModal').addEventListener('click', () => {
this.hideFileUploadModal();
});
// 拖放文件上传
const uploadArea = document.getElementById('uploadArea');
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.style.borderColor = '#0a84ff';
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.style.borderColor = '#38383a';
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.style.borderColor = '#38383a';
const file = e.dataTransfer.files[0];
if (file) {
this.handleFileSelect(file);
}
});
}
loadContacts() {
// 从API加载联系人
fetch('/api/users')
.then(response => response.json())
.then(contacts => {
this.contacts = contacts;
this.renderContacts();
})
.catch(error => {
console.error('加载联系人失败:', error);
});
}
renderContacts() {
const contactsList = document.getElementById('contactsList');
const chatList = document.getElementById('chatList');
contactsList.innerHTML = '';
chatList.innerHTML = '';
this.contacts.forEach(contact => {
// 联系人侧边栏
const contactItem = document.createElement('div');
contactItem.className = 'contact-item';
contactItem.innerHTML = `
<div class="chat-item-avatar">
<i class="fas fa-user-circle"></i>
</div>
<div class="chat-item-info">
<div class="chat-item-name">
${contact.name}
<span class="contact-status ${contact.online ? 'online' : 'offline'}"></span>
</div>
<div class="chat-item-last-message">${contact.org}</div>
</div>
`;
contactItem.addEventListener('click', () => {
this.selectContact(contact);
this.hideContactsSidebar();
});
contactsList.appendChild(contactItem);
// 聊天列表
const chatItem = document.createElement('div');
chatItem.className = 'chat-item';
chatItem.innerHTML = `
<div class="chat-item-avatar">
<i class="fas fa-user-circle"></i>
</div>
<div class="chat-item-info">
<div class="chat-item-name">
${contact.name}
<span class="contact-status ${contact.online ? 'online' : 'offline'}"></span>
</div>
<div class="chat-item-last-message">${contact.org}</div>
</div>
`;
chatItem.addEventListener('click', () => {
this.selectContact(contact);
});
chatList.appendChild(chatItem);
});
}
selectContact(contact) {
this.currentContact = contact;
// 更新UI
document.getElementById('partnerName').textContent = contact.name;
document.getElementById('partnerStatus').textContent =
contact.online ? '在线' : '离线';
document.getElementById('partnerStatus').style.color =
contact.online ? '#30d158' : '#6c6c70';
// 启用通话按钮
document.getElementById('voiceCallBtn').disabled = !contact.online;
// 显示聊天区域
this.showChatArea();
// 加载聊天历史(这里简化处理)
this.loadChatHistory(contact.account);
}
showChatArea() {
// 隐藏欢迎消息,显示聊天消息区域
const welcomeMsg = document.querySelector('.welcome-message');
if (welcomeMsg) {
welcomeMsg.style.display = 'none';
}
}
sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message || !this.currentContact) return;
// 发送消息
this.socket.emit('private_message', {
to: this.currentContact.account,
from: this.currentUser,
message: message
});
// 在界面上显示消息
this.addMessage({
from: this.currentUser,
message: message,
timestamp: Date.now() / 1000,
isOwn: true
});
// 清空输入框
input.value = '';
this.adjustTextareaHeight(input);
}
receiveMessage(data) {
// 如果是当前联系人的消息,直接显示
if (data.from === this.currentContact?.account) {
this.addMessage({
from: data.from,
message: data.message,
timestamp: data.timestamp,
isOwn: false
});
} else {
// 显示通知
this.showNotification(`收到来自 ${data.from} 的新消息`);
}
}
addMessage(data) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${data.isOwn ? 'sent' : 'received'}`;
const contact = this.contacts.find(c => c.account === data.from);
const contactName = contact ? contact.name : data.from;
const time = new Date(data.timestamp * 1000);
const timeStr = time.toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit'
});
messageDiv.innerHTML = `
<div class="message-avatar">
<i class="fas fa-user-circle"></i>
</div>
<div class="message-content">
<div class="message-text">${this.escapeHtml(data.message)}</div>
<div class="message-time">${timeStr}</div>
</div>
`;
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
adjustTextareaHeight(textarea) {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
}
startVoiceCall() {
if (!this.currentContact || !this.currentContact.online) return;
const callId = 'call_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
this.activeCall = {
id: callId,
partner: this.currentContact.account,
type: 'voice'
};
// 显示通话界面
this.showCallInterface();
document.getElementById('callPartnerName').textContent = this.currentContact.name;
document.getElementById('callStatus').textContent = '正在呼叫...';
document.getElementById('answerCallBtn').style.display = 'none';
// 通知对方
this.socket.emit('start_call', {
call_id: callId,
to: this.currentContact.account,
from: this.currentUser
});
// 开始获取本地音频流
this.startLocalStream();
}
handleIncomingCall(data) {
// 找到联系人
const contact = this.contacts.find(c => c.account === data.from);
if (!contact) return;
this.activeCall = {
id: data.call_id,
partner: data.from,
type: 'incoming'
};
// 显示来电界面
this.showCallInterface();
document.getElementById('callPartnerName').textContent = contact.name;
document.getElementById('callStatus').textContent = '来电中...';
document.getElementById('answerCallBtn').style.display = 'flex';
// 播放铃声
this.playRingtone();
}
answerCall() {
if (!this.activeCall) return;
this.stopRingtone();
// 通知对方已接听
this.socket.emit('answer_call', {
call_id: this.activeCall.id
});
// 开始通话计时
this.startCallTimer();
document.getElementById('callStatus').textContent = '通话中...';
document.getElementById('answerCallBtn').style.display = 'none';
// 开始获取本地音频流并在就绪后建立WebRTC连接
this.startLocalStream()
.then(() => {
this.setupWebRTCCall();
})
.catch(() => {
console.error('无法获取本地音频,无法建立通话');
});
}
endCall() {
if (!this.activeCall) return;
this.stopRingtone();
this.stopCallTimer();
// 通知对方结束通话
this.socket.emit('end_call', {
call_id: this.activeCall.id
});
// 关闭本地流
if (this.localStream) {
this.localStream.getTracks().forEach(track => track.stop());
this.localStream = null;
}
// 关闭PeerConnection
if (this.peerConnection) {
this.peerConnection.close();
this.peerConnection = null;
}
// 隐藏通话界面
this.hideCallInterface();
this.activeCall = null;
}
handleCallAccepted(data) {
if (!this.activeCall || this.activeCall.id !== data.call_id) return;
// 开始通话计时
this.startCallTimer();
document.getElementById('callStatus').textContent = '通话中...';
// 确保本地音频就绪后建立WebRTC连接并创建offer
this.startLocalStream()
.then(() => {
this.setupWebRTCCall();
})
.catch(() => {
console.error('无法获取本地音频,无法建立通话');
});
}
handleCallEnded(data) {
if (this.activeCall && this.activeCall.id === data.call_id) {
this.endCall();
}
}
showCallInterface() {
document.getElementById('callInterface').style.display = 'flex';
}
hideCallInterface() {
document.getElementById('callInterface').style.display = 'none';
}
startCallTimer() {
this.callStartTime = Date.now();
this.callTimer = setInterval(() => {
const elapsed = Date.now() - this.callStartTime;
const minutes = Math.floor(elapsed / 60000);
const seconds = Math.floor((elapsed % 60000) / 1000);
document.getElementById('callTimer').textContent =
`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}, 1000);
}
stopCallTimer() {
if (this.callTimer) {
clearInterval(this.callTimer);
this.callTimer = null;
}
}
playRingtone() {
// 这里可以添加铃声播放逻辑
console.log('播放铃声');
}
stopRingtone() {
// 停止铃声
console.log('停止铃声');
}
setupWebRTC() {
// 简单的WebRTC配置
this.peerConnectionConfig = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' }
]
};
}
startLocalStream() {
return navigator.mediaDevices.getUserMedia({
audio: true,
video: false
})
.then(stream => {
this.localStream = stream;
const localAudio = document.getElementById('localAudio');
if (localAudio) {
localAudio.srcObject = stream;
}
return stream;
})
.catch(error => {
console.error('获取音频流失败:', error);
throw error;
});
}
setupWebRTCCall() {
this.peerConnection = new RTCPeerConnection(this.peerConnectionConfig);
// 添加本地音频流
if (this.localStream) {
this.localStream.getTracks().forEach(track => {
this.peerConnection.addTrack(track, this.localStream);
});
}
// 处理远程流
this.peerConnection.ontrack = (event) => {
const remoteAudio = document.getElementById('remoteAudio');
if (remoteAudio) {
remoteAudio.srcObject = event.streams[0];
}
};
// 处理ICE候选
this.peerConnection.onicecandidate = (event) => {
if (event.candidate) {
this.socket.emit('webrtc_signal', {
to: this.activeCall.partner,
signal: {
type: 'candidate',
candidate: event.candidate
}
});
}
};
// 如果是发起方,创建offer
if (this.activeCall.type === 'voice') {
this.peerConnection.createOffer()
.then(offer => this.peerConnection.setLocalDescription(offer))
.then(() => {
this.socket.emit('webrtc_signal', {
to: this.activeCall.partner,
signal: {
type: 'offer',
sdp: this.peerConnection.localDescription
}
});
})
.catch(error => {
console.error('创建offer失败:', error);
});
}
}
handleWebRTCSignal(signal) {
if (!this.peerConnection) return;
switch (signal.type) {
case 'offer': {
const desc = signal.sdp || signal;
this.peerConnection.setRemoteDescription(new RTCSessionDescription(desc))
.then(() => this.peerConnection.createAnswer())
.then(answer => this.peerConnection.setLocalDescription(answer))
.then(() => {
this.socket.emit('webrtc_signal', {
to: this.activeCall.partner,
signal: {
type: 'answer',
sdp: this.peerConnection.localDescription
}
});
})
.catch(error => {
console.error('处理offer失败:', error);
});
break;
}
case 'answer': {
const desc = signal.sdp || signal;
this.peerConnection.setRemoteDescription(new RTCSessionDescription(desc))
.catch(error => {
console.error('处理answer失败:', error);
});
break;
}
case 'candidate': {
const candidate = signal.candidate || signal;
this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
.catch(error => {
console.error('添加ICE候选失败:', error);
});
break;
}
}
}
showFileUploadModal() {
document.getElementById('fileUploadModal').style.display = 'flex';
}
hideFileUploadModal() {
document.getElementById('fileUploadModal').style.display = 'none';
document.getElementById('filePreview').innerHTML = '';
document.getElementById('fileInput').value = '';
}
async handleFileSelect(file) {
if (!file) return;
// 显示文件预览
const filePreview = document.getElementById('filePreview');
filePreview.innerHTML = `
<div class="file-item">
<div class="file-icon">
<i class="fas fa-file"></i>
</div>
<div class="file-info">
<div class="file-name">${file.name}</div>
<div class="file-size">${this.formatFileSize(file.size)}</div>
</div>
<button class="upload-btn" id="uploadFileBtn">发送</button>
</div>
`;
// 添加发送按钮事件
document.getElementById('uploadFileBtn').addEventListener('click', async () => {
await this.uploadFile(file);
});
}
async uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
// 发送文件消息
this.socket.emit('file_uploaded', {
to: this.currentContact.account,
from: this.currentUser,
filename: result.filename,
url: result.url
});
// 显示文件消息
this.addMessage({
from: this.currentUser,
message: `[文件] ${result.filename}`,
timestamp: Date.now() / 1000,
isOwn: true
});
this.hideFileUploadModal();
} else {
alert(result.message);
}
} catch (error) {
console.error('文件上传失败:', error);
alert('文件上传失败');
}
}
showFileNotification(data) {
// 如果是当前联系人的文件,显示消息
if (data.from === this.currentContact?.account) {
this.addMessage({
from: data.from,
message: `[文件] ${data.filename}`,
timestamp: data.timestamp,
isOwn: false
});
// 添加下载链接
const messagesContainer = document.getElementById('chatMessages');
const fileLink = document.createElement('div');
fileLink.className = 'message received';
fileLink.innerHTML = `
<div class="message-content">
<div class="message-text">
<a href="${data.url}" target="_blank" style="color: #0a84ff; text-decoration: none;">
<i class="fas fa-download"></i> 下载文件: ${data.filename}
</a>
</div>
</div>
`;
messagesContainer.appendChild(fileLink);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
} else {
this.showNotification(`收到来自 ${data.from} 的文件: ${data.filename}`);
}
}
showContactsSidebar() {
document.getElementById('contactsSidebar').classList.add('active');
}
hideContactsSidebar() {
document.getElementById('contactsSidebar').classList.remove('active');
}
showFilesSidebar() {
this.loadFiles();
document.getElementById('filesSidebar').classList.add('active');
}
hideFilesSidebar() {
document.getElementById('filesSidebar').classList.remove('active');
}
async loadFiles() {
try {
const response = await fetch('/api/files');
const files = await response.json();
this.renderFiles(files);
} catch (error) {
console.error('加载文件失败:', error);
}
}
renderFiles(files) {
const filesList = document.getElementById('filesList');
filesList.innerHTML = '';
files.forEach(file => {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
fileItem.innerHTML = `
<div class="file-icon">
<i class="fas fa-file"></i>
</div>
<div class="file-info">
<div class="file-name">${file.filename}</div>
<div class="file-size">${this.formatFileSize(file.size)}</div>
<div class="file-uploader">上传者: ${file.uploader}</div>
</div>
<a href="${file.url}" target="_blank" class="upload-btn">
<i class="fas fa-download"></i>
</a>
`;
filesList.appendChild(fileItem);
});
}
updateUserStatus(account, online) {
// 更新联系人状态
const contact = this.contacts.find(c => c.account === account);
if (contact) {
contact.online = online;
this.renderContacts();
// 如果是当前联系人,更新状态显示
if (this.currentContact && this.currentContact.account === account) {
document.getElementById('partnerStatus').textContent = online ? '在线' : '离线';
document.getElementById('partnerStatus').style.color =
online ? '#30d158' : '#6c6c70';
document.getElementById('voiceCallBtn').disabled = !online;
}
}
}
formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
showNotification(message) {
// 简单的浏览器通知
if ('Notification' in window && Notification.permission === 'granted') {
new Notification('Web WeChat', {
body: message,
icon: '/static/favicon.ico'
});
}
}
loadChatHistory(account) {
// 这里可以加载聊天历史
const messagesContainer = document.getElementById('chatMessages');
messagesContainer.innerHTML = '';
// 暂时显示一条欢迎消息
if (messagesContainer.children.length === 0) {
const welcomeMsg = document.createElement('div');
welcomeMsg.className = 'welcome-message';
welcomeMsg.innerHTML = `
<i class="fas fa-comment-dots"></i>
<h3>开始与 ${this.currentContact.name} 聊天</h3>
<p>输入消息开始对话</p>
`;
messagesContainer.appendChild(welcomeMsg);
}
}
}
// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
window.wechatApp = new WebWeChat();
// 请求通知权限
if ('Notification' in window) {
Notification.requestPermission();
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 547 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 547 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

@@ -0,0 +1,2 @@
//端口卸载下一行(第二行)
8080
@@ -0,0 +1,2 @@
//端口卸载下一行(第二行)
8080
@@ -0,0 +1,2 @@
//端口卸载下一行(第二行)
8080
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB