chore: refact webRTC relative logic and update npm module
This commit is contained in:
4
.env_template
Normal file
4
.env_template
Normal file
@@ -0,0 +1,4 @@
|
||||
STUN_URL=''
|
||||
TURN_URL=''
|
||||
TURN_USERNAME=''
|
||||
TURN_CREDENTIAL=''
|
||||
64
.gitignore
vendored
64
.gitignore
vendored
@@ -1,30 +1,34 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
|
||||
# dev environment variables
|
||||
.env
|
||||
9178
package-lock.json
generated
9178
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
72
package.json
72
package.json
@@ -1,34 +1,38 @@
|
||||
{
|
||||
"name": "myplayer_vue",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"proxy": "node proxy.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.6",
|
||||
"crypto-js": "^4.2.0",
|
||||
"dplayer": "^1.27.1",
|
||||
"element-plus": "^2.9.4",
|
||||
"express": "^4.21.2",
|
||||
"hls.js": "^1.5.20",
|
||||
"idb": "^8.0.2",
|
||||
"node-fetch": "^3.3.2",
|
||||
"pinia": "^3.0.1",
|
||||
"pinia-plugin-persistedstate": "^4.2.0",
|
||||
"video.js": "^8.21.0",
|
||||
"videojs-vtt.js": "^0.15.5",
|
||||
"vue": "^3.5.13",
|
||||
"vue-axios": "^3.5.2",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.11",
|
||||
"vite-plugin-vue-devtools": "^7.7.1"
|
||||
}
|
||||
}
|
||||
{
|
||||
"name": "myplayer_vue",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"proxy": "node proxy.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.6",
|
||||
"crypto-js": "^4.2.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"dplayer": "^1.27.1",
|
||||
"element-plus": "^2.9.4",
|
||||
"express": "^4.21.2",
|
||||
"hls.js": "^1.5.20",
|
||||
"idb": "^8.0.2",
|
||||
"node-fetch": "^3.3.2",
|
||||
"pinia": "^3.0.1",
|
||||
"pinia-plugin-persistedstate": "^4.2.0",
|
||||
"video.js": "^8.21.0",
|
||||
"videojs-vtt.js": "^0.15.5",
|
||||
"vue": "^3.5.13",
|
||||
"vue-axios": "^3.5.2",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.11",
|
||||
"vite-plugin-vue-devtools": "^7.7.1"
|
||||
},
|
||||
"overrides": {
|
||||
"axios": "^1.13.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,162 +1,159 @@
|
||||
<template>
|
||||
<nav class="navbar">
|
||||
<div class="navbar-left">
|
||||
<router-link to="/home" class="navbar-logo">
|
||||
<img :src="logo" alt="MyPlayer" />
|
||||
</router-link>
|
||||
</div>
|
||||
<div class="navbar-right">
|
||||
<router-link to="/home/search">搜索</router-link>
|
||||
<router-link to="/home/friends">好友</router-link>
|
||||
<router-link to="/home/group">群聊</router-link>
|
||||
<router-link to="/home/playroom">Playroom</router-link>
|
||||
<div class="more-dropdown" @click="toggleDropdown" @blur="closeDropdown">
|
||||
更多
|
||||
<ul v-if="isDropdownOpen" class="dropdown-content">
|
||||
<li>设置</li>
|
||||
<li @click="aboutUs">关于我们</li>
|
||||
<li>帮助</li>
|
||||
<li @click="logout">退出登录</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted, initCustomFormatter } from 'vue';
|
||||
import logo from '../assets/logo.png';
|
||||
import { onlineSocketStore } from '@/store/Online';
|
||||
import router from '@/router';
|
||||
import { voiceStore } from '@/store/Voice';
|
||||
import { groupMessageStore } from '@/store/message.ts';
|
||||
import { userInfoStore } from '@/store/user';
|
||||
|
||||
const userInfo = userInfoStore()
|
||||
const voice = voiceStore()
|
||||
const socket = onlineSocketStore()
|
||||
const groupMessage = groupMessageStore()
|
||||
|
||||
|
||||
const isDropdownOpen = ref(false); // 控制下拉框的显示与隐藏
|
||||
|
||||
const toggleDropdown = () => {
|
||||
isDropdownOpen.value = !isDropdownOpen.value; // 切换下拉框的显示状态
|
||||
};
|
||||
|
||||
const closeDropdown = () => {
|
||||
isDropdownOpen.value = false; // 关闭下拉框
|
||||
};
|
||||
|
||||
// 监听全局点击事件
|
||||
const handleGlobalClick = (event) => {
|
||||
// 检查点击是否发生在下拉框外部
|
||||
if (!event.target.closest('.more-dropdown')) {
|
||||
closeDropdown();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleGlobalClick);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleGlobalClick);
|
||||
});
|
||||
|
||||
|
||||
//退出登录逻辑
|
||||
const logout = () => {
|
||||
//保存群聊消息
|
||||
groupMessage.saveMessagesHistory(socket.u_id,groupMessage.g_id)
|
||||
// 清除用户全局信息
|
||||
userInfo.clearUserInfo();
|
||||
localStorage.clear();
|
||||
// 断开websocket链接
|
||||
voice.disconnect();
|
||||
socket.disconnect();
|
||||
// 跳转到登录页面
|
||||
window.location.href = '/';
|
||||
|
||||
};
|
||||
|
||||
const aboutUs = () => {
|
||||
router.push('/home/about')
|
||||
}
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.navbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
padding: 10px 20px;
|
||||
background-color: #60605e;
|
||||
color: #fff;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.navbar-left,
|
||||
.navbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 10%;
|
||||
margin-left: 10%;
|
||||
}
|
||||
|
||||
.navbar-logo img {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.navbar a {
|
||||
color: #fff;
|
||||
margin: 0 10px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.navbar a.router-link-active {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.more-dropdown {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropdown-content {
|
||||
position: absolute;
|
||||
width: 100px;
|
||||
margin-top: 22px;
|
||||
right: -50px;
|
||||
color: #fff;
|
||||
background-color: #444444;
|
||||
border: 1px solid #000000;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
|
||||
padding: 5px;
|
||||
z-index: 1000;
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
.dropdown-content a {
|
||||
display: block;
|
||||
margin: 5px 0;
|
||||
}
|
||||
|
||||
.dropdown-content li {
|
||||
height: 40px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.dropdown-content li:hover {
|
||||
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
}
|
||||
<template>
|
||||
<nav class="navbar">
|
||||
<div class="navbar-left">
|
||||
<router-link to="/home" class="navbar-logo">
|
||||
<img :src="logo" alt="MyPlayer" />
|
||||
</router-link>
|
||||
</div>
|
||||
<div class="navbar-right">
|
||||
<router-link to="/home/search">搜索</router-link>
|
||||
<router-link to="/home/friends">好友</router-link>
|
||||
<router-link to="/home/group">群聊</router-link>
|
||||
<router-link to="/home/playroom">Playroom</router-link>
|
||||
<div class="more-dropdown" @click="toggleDropdown" @blur="closeDropdown">
|
||||
更多
|
||||
<ul v-if="isDropdownOpen" class="dropdown-content">
|
||||
<li>设置</li>
|
||||
<li @click="aboutUs">关于我们</li>
|
||||
<li>帮助</li>
|
||||
<li @click="logout">退出登录</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import logo from '../assets/logo.png';
|
||||
import { onlineSocketStore } from '@/store/Online';
|
||||
import router from '@/router';
|
||||
import { groupMessageStore } from '@/store/message.ts';
|
||||
import { userInfoStore } from '@/store/user';
|
||||
|
||||
const userInfo = userInfoStore()
|
||||
const socket = onlineSocketStore()
|
||||
const groupMessage = groupMessageStore()
|
||||
|
||||
|
||||
const isDropdownOpen = ref(false); // 控制下拉框的显示与隐藏
|
||||
|
||||
const toggleDropdown = () => {
|
||||
isDropdownOpen.value = !isDropdownOpen.value; // 切换下拉框的显示状态
|
||||
};
|
||||
|
||||
const closeDropdown = () => {
|
||||
isDropdownOpen.value = false; // 关闭下拉框
|
||||
};
|
||||
|
||||
// 监听全局点击事件
|
||||
const handleGlobalClick = (event) => {
|
||||
// 检查点击是否发生在下拉框外部
|
||||
if (!event.target.closest('.more-dropdown')) {
|
||||
closeDropdown();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleGlobalClick);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleGlobalClick);
|
||||
});
|
||||
|
||||
|
||||
//退出登录逻辑
|
||||
const logout = () => {
|
||||
//保存群聊消息
|
||||
groupMessage.saveMessagesHistory(socket.u_id,groupMessage.g_id)
|
||||
// 清除用户全局信息
|
||||
userInfo.clearUserInfo();
|
||||
localStorage.clear();
|
||||
// 断开websocket链接
|
||||
socket.disconnect();
|
||||
// 跳转到登录页面
|
||||
window.location.href = '/';
|
||||
|
||||
};
|
||||
|
||||
const aboutUs = () => {
|
||||
router.push('/home/about')
|
||||
}
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.navbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
padding: 10px 20px;
|
||||
background-color: #60605e;
|
||||
color: #fff;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.navbar-left,
|
||||
.navbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 10%;
|
||||
margin-left: 10%;
|
||||
}
|
||||
|
||||
.navbar-logo img {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.navbar a {
|
||||
color: #fff;
|
||||
margin: 0 10px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.navbar a.router-link-active {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.more-dropdown {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropdown-content {
|
||||
position: absolute;
|
||||
width: 100px;
|
||||
margin-top: 22px;
|
||||
right: -50px;
|
||||
color: #fff;
|
||||
background-color: #444444;
|
||||
border: 1px solid #000000;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
|
||||
padding: 5px;
|
||||
z-index: 1000;
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
.dropdown-content a {
|
||||
display: block;
|
||||
margin: 5px 0;
|
||||
}
|
||||
|
||||
.dropdown-content li {
|
||||
height: 40px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.dropdown-content li:hover {
|
||||
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
}
|
||||
</style>
|
||||
@@ -1,153 +1,152 @@
|
||||
<template>
|
||||
<el-button class="telegram-btn" @click="showTelegramPanel">
|
||||
<el-icon>
|
||||
<Mic />
|
||||
</el-icon>
|
||||
<div class="telegramTag"></div>
|
||||
</el-button>
|
||||
|
||||
<div class="voice" v-if="onCall.panel">
|
||||
<div>
|
||||
<div class="profilebox">
|
||||
<img :src="onCall.target.avatar" alt="头像">
|
||||
</div>
|
||||
<div class="infobox">
|
||||
<p>{{ onCall.target.name }}</p>
|
||||
</div>
|
||||
<div class="buttonsbox">
|
||||
<button @click="answer" v-if="!onCall.from">
|
||||
接听
|
||||
</button>
|
||||
<button @click="hangup">
|
||||
挂断
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<el-button @click="playRemoteAudio">没有声音?试试我</el-button>
|
||||
</div>
|
||||
<audio ref="remoteAudio" autoplay></audio>
|
||||
|
||||
</template>
|
||||
<script setup>
|
||||
import { userInfoStore } from '@/store/store';
|
||||
import { voiceStore } from '@/store/Voice';
|
||||
import { onCallStore } from '@/store/VoiceTarget';
|
||||
import { Mic } from '@element-plus/icons-vue';
|
||||
import { ref, onMounted, onBeforeUnmount } from 'vue';
|
||||
|
||||
const voice = voiceStore();
|
||||
const onCall = onCallStore();
|
||||
const userinfo = userInfoStore()
|
||||
|
||||
const localAudio = ref(null);
|
||||
const remoteAudio = ref(null);
|
||||
|
||||
onMounted(() => {
|
||||
onCall.setRemoteElement(remoteAudio.value);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
// 清理音频流和元素
|
||||
if (localAudio.value.srcObject) {
|
||||
localAudio.value.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
if (remoteAudio.value.srcObject) {
|
||||
remoteAudio.value.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
})
|
||||
|
||||
const answer = () => {
|
||||
console.log("接听");
|
||||
onCall.callingOff();
|
||||
onCall.fromOn();
|
||||
voice.pickup(userinfo.user.u_id, onCall.target.u_id)
|
||||
}
|
||||
|
||||
const hangup = () => {
|
||||
voice.hangup();
|
||||
}
|
||||
|
||||
const showTelegramPanel = () => {
|
||||
onCall.panel = !onCall.panel;
|
||||
}
|
||||
|
||||
const playRemoteAudio = () => {
|
||||
const audio = document.getElementById("remoteAudio");
|
||||
if (audio) {
|
||||
audio.play().catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
<style>
|
||||
.voice {
|
||||
position: fixed;
|
||||
top: 210px;
|
||||
right: 100px;
|
||||
width: 300px;
|
||||
height: 400px;
|
||||
background-color: #d7d7d7;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
.profilebox {
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.profilebox img {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.infobox {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 18px;
|
||||
color: #646464;
|
||||
}
|
||||
|
||||
.buttonsbox {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.buttonsbox button {
|
||||
margin: 0 20px 0 20px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.telegram-btn {
|
||||
position: fixed;
|
||||
top: 45%;
|
||||
right: 0;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.telegramTag {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background-color: #f00;
|
||||
}
|
||||
<template>
|
||||
<el-button class="telegram-btn" @click="showTelegramPanel">
|
||||
<el-icon>
|
||||
<Mic />
|
||||
</el-icon>
|
||||
<div class="telegramTag"></div>
|
||||
</el-button>
|
||||
|
||||
<div class="voice" v-if="onCall.panel">
|
||||
<div>
|
||||
<div class="profilebox">
|
||||
<img :src="onCall.target.avatar" alt="头像">
|
||||
</div>
|
||||
<div class="infobox">
|
||||
<p>{{ onCall.target.name }}</p>
|
||||
</div>
|
||||
<div class="buttonsbox">
|
||||
<button @click="answer" v-if="!onCall.from">
|
||||
接听
|
||||
</button>
|
||||
<button @click="denyCall(userinfo.user.id, onCall.target.u_id)" v-if="!onCall.from">
|
||||
拒绝
|
||||
</button>
|
||||
<button @click="hangupCall(userinfo.user.id, onCall.target.u_id)" v-if="onCall.from">
|
||||
挂断
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<el-button @click="playRemoteAudio">没有声音?试试我</el-button>
|
||||
</div>
|
||||
<audio ref="remoteAudio" id="remoteAudio" autoplay playsinline></audio>
|
||||
|
||||
</template>
|
||||
<script setup>
|
||||
import { userInfoStore } from '@/store/user';
|
||||
import { onCallStore } from '@/store/VoiceTarget';
|
||||
import { Mic } from '@element-plus/icons-vue';
|
||||
import { ref, onMounted, onBeforeUnmount } from 'vue';
|
||||
import { denyCall, hangupCall,sendOffer } from '@/store/Voice.ts';
|
||||
|
||||
const onCall = onCallStore();
|
||||
const userinfo = userInfoStore()
|
||||
|
||||
const localAudio = ref(null);
|
||||
const remoteAudio = ref(null);
|
||||
|
||||
onMounted(() => {
|
||||
onCall.setRemoteElement(remoteAudio.value);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
// 清理音频流和元素
|
||||
if (localAudio.value && localAudio.value.srcObject) {
|
||||
localAudio.value.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
if (remoteAudio.value && remoteAudio.value.srcObject) {
|
||||
remoteAudio.value.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
})
|
||||
|
||||
const answer = async () => {
|
||||
console.log("接听");
|
||||
onCall.callingOff();
|
||||
onCall.fromOn();
|
||||
// voice.pickup(userinfo.user.id, onCall.target.u_id)
|
||||
await sendOffer(userinfo.user.id, onCall.target.u_id);
|
||||
}
|
||||
|
||||
|
||||
const showTelegramPanel = () => {
|
||||
onCall.panel = !onCall.panel;
|
||||
}
|
||||
|
||||
const playRemoteAudio = () => {
|
||||
const audio = remoteAudio.value;
|
||||
if (!audio) return;
|
||||
audio.play().catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
<style>
|
||||
.voice {
|
||||
position: fixed;
|
||||
top: 210px;
|
||||
right: 100px;
|
||||
width: 300px;
|
||||
height: 400px;
|
||||
background-color: #d7d7d7;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
.profilebox {
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.profilebox img {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.infobox {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 18px;
|
||||
color: #646464;
|
||||
}
|
||||
|
||||
.buttonsbox {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.buttonsbox button {
|
||||
margin: 0 20px 0 20px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.telegram-btn {
|
||||
position: fixed;
|
||||
top: 45%;
|
||||
right: 0;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.telegramTag {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background-color: #f00;
|
||||
}
|
||||
</style>
|
||||
@@ -1,72 +1,72 @@
|
||||
<template>
|
||||
<router-link to="/home/user" v-if="userinfo.user.u_avatar" class="user-profile-link">
|
||||
<div class="user-profile">
|
||||
<img :src="userinfo.user.u_avatar" alt="User Avatar" />
|
||||
<div :class="['status-dot', statusClass]"></div>
|
||||
</div>
|
||||
</router-link>
|
||||
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { userInfoStore } from '@/store/store';
|
||||
|
||||
const userinfo = userInfoStore();
|
||||
|
||||
const isLoggedIn = ref(true); // 假设用户已登录
|
||||
|
||||
const statusClass = computed(() => {
|
||||
return isLoggedIn.value ? 'online' : 'offline';
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.user-profile-link {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
/* 去掉链接的下划线 */
|
||||
}
|
||||
|
||||
.user-profile {
|
||||
position: fixed;
|
||||
bottom: 30px;
|
||||
right: 30px;
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
z-index: 500;
|
||||
|
||||
}
|
||||
|
||||
.user-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.online {
|
||||
background-color: green;
|
||||
/* 在线状态 */
|
||||
}
|
||||
|
||||
.offline {
|
||||
background-color: red;
|
||||
/* 离线状态 */
|
||||
}
|
||||
<template>
|
||||
<router-link to="/home/user" v-if="userinfo.user.u_avatar" class="user-profile-link">
|
||||
<div class="user-profile">
|
||||
<img :src="userinfo.user.u_avatar" alt="User Avatar" />
|
||||
<div :class="['status-dot', statusClass]"></div>
|
||||
</div>
|
||||
</router-link>
|
||||
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { userInfoStore } from '@/store/user.ts';
|
||||
|
||||
const userinfo = userInfoStore();
|
||||
|
||||
const isLoggedIn = ref(true); // 假设用户已登录
|
||||
|
||||
const statusClass = computed(() => {
|
||||
return isLoggedIn.value ? 'online' : 'offline';
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.user-profile-link {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
/* 去掉链接的下划线 */
|
||||
}
|
||||
|
||||
.user-profile {
|
||||
position: fixed;
|
||||
bottom: 30px;
|
||||
right: 30px;
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
z-index: 500;
|
||||
|
||||
}
|
||||
|
||||
.user-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.online {
|
||||
background-color: green;
|
||||
/* 在线状态 */
|
||||
}
|
||||
|
||||
.offline {
|
||||
background-color: red;
|
||||
/* 离线状态 */
|
||||
}
|
||||
</style>
|
||||
@@ -1,37 +1,42 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { connectWebSocket, disconnectWebSocket, sendMessage, setIsManualClose } from '@/websocket/onlineSocket'
|
||||
import { messageStore } from './message'
|
||||
|
||||
const message = messageStore()
|
||||
|
||||
export const onlineSocketStore = defineStore('onlineSocket', {
|
||||
state: () => ({
|
||||
isConnected: false,
|
||||
hasGotMessage: false,
|
||||
id: ''
|
||||
}),
|
||||
|
||||
actions: {
|
||||
connect(id) {
|
||||
this.id = id;
|
||||
if (this.isConnected === true) return
|
||||
connectWebSocket();
|
||||
this.isConnected = true;
|
||||
if (!this.hasGotMessage) {
|
||||
message.loadMessagesHistory(this.id)
|
||||
this.hasGotMessage = true
|
||||
}
|
||||
},
|
||||
disconnect() {
|
||||
setIsManualClose(true);
|
||||
disconnectWebSocket();
|
||||
this.isConnected = false;
|
||||
if (this.hasGotMessage) {
|
||||
message.saveMessagesHistory(this.id)
|
||||
}
|
||||
},
|
||||
send(message) {
|
||||
sendMessage(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
import { defineStore } from 'pinia'
|
||||
import { connectWebSocket, disconnectWebSocket, sendMessage, setIsManualClose } from '@/websocket/onlineSocket'
|
||||
import { messageStore } from './message'
|
||||
|
||||
const message = messageStore()
|
||||
|
||||
export const onlineSocketStore = defineStore('onlineSocket', {
|
||||
state: () => ({
|
||||
isConnected: false,
|
||||
hasGotMessage: false,
|
||||
id: ''
|
||||
}),
|
||||
|
||||
actions: {
|
||||
connect(id: number) {
|
||||
this.id = id;
|
||||
if (this.isConnected === true) return
|
||||
connectWebSocket();
|
||||
this.isConnected = true;
|
||||
if (!this.hasGotMessage) {
|
||||
message.loadMessagesHistory(this.id)
|
||||
this.hasGotMessage = true
|
||||
}
|
||||
},
|
||||
disconnect() {
|
||||
setIsManualClose(true);
|
||||
disconnectWebSocket();
|
||||
this.isConnected = false;
|
||||
if (this.hasGotMessage) {
|
||||
message.saveMessagesHistory(this.id)
|
||||
}
|
||||
},
|
||||
send(message: any) {
|
||||
try {
|
||||
sendMessage(message);
|
||||
} catch (error) {
|
||||
console.error('Failed to stringify message:', error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,50 +0,0 @@
|
||||
import { connectVoicesocket, disconnectVoicesocket, sendMessage, hangup } from "@/websocket/voiceSocket";
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const voiceStore = defineStore("voice", {
|
||||
state: () => ({
|
||||
isConnected: false
|
||||
}),
|
||||
actions: {
|
||||
connect() {
|
||||
connectVoicesocket();
|
||||
this.isConnected = true;
|
||||
},
|
||||
disconnect() {
|
||||
disconnectVoicesocket();
|
||||
this.isConnected = false;
|
||||
},
|
||||
startCall(from, from_name, from_avatar, to) {
|
||||
if (this.isConnected) {
|
||||
const message = {
|
||||
type: "incomingcall",
|
||||
from: from,
|
||||
from_name: from_name,
|
||||
from_avatar: from_avatar,
|
||||
to: to
|
||||
}
|
||||
sendMessage(JSON.stringify(message))
|
||||
} else {
|
||||
console.log("voice socket is not connected")
|
||||
}
|
||||
},
|
||||
pickup(from,to){
|
||||
if (this.isConnected) {
|
||||
const message ={
|
||||
type: "pickup",
|
||||
from: from,
|
||||
to: to
|
||||
}
|
||||
sendMessage(JSON.stringify(message))
|
||||
} else {
|
||||
console.log("voice socket is not connected")
|
||||
}
|
||||
},
|
||||
hangup(){
|
||||
hangup()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
)
|
||||
235
src/store/Voice.ts
Normal file
235
src/store/Voice.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { sendMessage } from "@/websocket/onlineSocket";
|
||||
import { onCallStore } from "@/store/VoiceTarget";
|
||||
import { ref } from "vue";
|
||||
|
||||
const iceserver = {
|
||||
iceServers: [
|
||||
{
|
||||
urls: process.env.STUN_URL,
|
||||
},
|
||||
{
|
||||
urls: process.env.TURN_URL,
|
||||
username: process.env.TURN_USERNAME,
|
||||
credential: process.env.TURN_CREDENTIAL,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
interface message {
|
||||
cmd: "VOICE_ICE_CANDIDATE" | "VOICE_SDP_OFFER" | "VOICE_SDP_ANSWER",
|
||||
from: number,
|
||||
to: number,
|
||||
content: any,
|
||||
}
|
||||
|
||||
const oncall = onCallStore();
|
||||
|
||||
const RTCpeerConnection = ref(null);
|
||||
|
||||
const localstream = ref(null);
|
||||
const remotestream = ref<MediaStream | null>(null);
|
||||
|
||||
// 本地候选:为了避免“绑定 onicecandidate 太晚”导致丢失,统一先缓存,等 remoteDescription 就绪后再发送
|
||||
const pendingLocalCandidates = ref<any[]>([]);
|
||||
// 远端候选:避免远端 candidate 早到但 remoteDescription 未 set 导致 addIceCandidate 失败
|
||||
const pendingRemoteCandidates = ref<any[]>([]);
|
||||
|
||||
// 当前会话对端信息(用于发送 ICE 时带上 from/to)
|
||||
const currentFrom = ref<number | null>(null);
|
||||
const currentTo = ref<number | null>(null);
|
||||
|
||||
const canSendIceNow = () => {
|
||||
const pc: any = RTCpeerConnection.value;
|
||||
return (
|
||||
!!pc &&
|
||||
!!pc.localDescription &&
|
||||
!!pc.remoteDescription &&
|
||||
currentFrom.value !== null &&
|
||||
currentTo.value !== null
|
||||
);
|
||||
};
|
||||
|
||||
const flushLocalCandidatesIfReady = () => {
|
||||
if (!canSendIceNow()) return;
|
||||
if (pendingLocalCandidates.value.length === 0) return;
|
||||
|
||||
pendingLocalCandidates.value.forEach((candidate) => {
|
||||
const message: message = {
|
||||
cmd: "VOICE_ICE_CANDIDATE",
|
||||
from: currentFrom.value as number,
|
||||
to: currentTo.value as number,
|
||||
content: candidate,
|
||||
};
|
||||
sendMessage(message);
|
||||
});
|
||||
pendingLocalCandidates.value = [];
|
||||
};
|
||||
|
||||
const flushRemoteCandidatesIfReady = async () => {
|
||||
const pc: any = RTCpeerConnection.value;
|
||||
if (!pc || !pc.remoteDescription) return;
|
||||
if (pendingRemoteCandidates.value.length === 0) return;
|
||||
|
||||
for (const c of pendingRemoteCandidates.value) {
|
||||
await pc.addIceCandidate(new RTCIceCandidate(c));
|
||||
}
|
||||
pendingRemoteCandidates.value = [];
|
||||
};
|
||||
|
||||
const getlocalStream = async () => {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
console.log("获取本地音频流成功");
|
||||
return stream;
|
||||
// // 获取音频和视频轨道
|
||||
// const audioTrack = stream.getAudioTracks()[0];
|
||||
// // 将轨道添加到 RTCPeerConnection
|
||||
// peerConnection.addTrack(audioTrack, stream);
|
||||
};
|
||||
|
||||
const closeLocalStream = (stream: MediaStream) => {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
export const initRTCconnection = async () => {
|
||||
RTCpeerConnection.value = new RTCPeerConnection(iceserver);
|
||||
localstream.value = await getlocalStream();
|
||||
RTCpeerConnection.value.addTrack(localstream.value.getAudioTracks()[0], localstream.value);
|
||||
|
||||
// 必须尽早绑定,否则可能在 setLocalDescription 后就把 candidate 产完了
|
||||
RTCpeerConnection.value.onicecandidate = (event: { candidate: any }) => {
|
||||
if (!event.candidate) return;
|
||||
pendingLocalCandidates.value.push(event.candidate);
|
||||
flushLocalCandidatesIfReady();
|
||||
};
|
||||
|
||||
// 远端音频:收到 track 后把 MediaStream 绑定到 UI 的 <audio>
|
||||
RTCpeerConnection.value.ontrack = (event: RTCTrackEvent) => {
|
||||
// 优先用浏览器提供的 streams[0];否则手动聚合 track
|
||||
let stream = event.streams && event.streams[0] ? event.streams[0] : null;
|
||||
if (!stream) {
|
||||
if (!remotestream.value) remotestream.value = new MediaStream();
|
||||
if (event.track) remotestream.value.addTrack(event.track);
|
||||
stream = remotestream.value;
|
||||
}
|
||||
if (stream) {
|
||||
oncall.setRemoteStream(stream);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const sendOffer = async (from: number,to: number) => {
|
||||
if (!RTCpeerConnection.value) {
|
||||
await initRTCconnection();
|
||||
};
|
||||
currentFrom.value = from;
|
||||
currentTo.value = to;
|
||||
const offer = await RTCpeerConnection.value.createOffer();
|
||||
await RTCpeerConnection.value.setLocalDescription(offer);
|
||||
const message: message = {
|
||||
cmd: "VOICE_SDP_OFFER",
|
||||
from: from,
|
||||
to: to,
|
||||
content: offer
|
||||
}
|
||||
sendMessage(message);
|
||||
}
|
||||
|
||||
export const handleOffer = async (offer: any, from: number, to: number) => {
|
||||
if (!RTCpeerConnection.value) {
|
||||
await initRTCconnection();
|
||||
}
|
||||
// 这里是“我收到对方 offer”,因此我这端的 from/to 应该是 (to -> from)
|
||||
currentFrom.value = to;
|
||||
currentTo.value = from;
|
||||
await RTCpeerConnection.value.setRemoteDescription(new RTCSessionDescription(offer));
|
||||
await flushRemoteCandidatesIfReady();
|
||||
const answer = await RTCpeerConnection.value.createAnswer();
|
||||
await RTCpeerConnection.value.setLocalDescription(answer);
|
||||
const message: message = {
|
||||
cmd: "VOICE_SDP_ANSWER",
|
||||
from: to,
|
||||
to: from,
|
||||
content: answer
|
||||
}
|
||||
sendMessage(message);
|
||||
// remoteDescription + localDescription 都已具备,允许发送本地候选
|
||||
flushLocalCandidatesIfReady();
|
||||
}
|
||||
|
||||
export const handleAnswer = async (answer: any, from: number, to: number) => {
|
||||
if (!RTCpeerConnection.value)
|
||||
{
|
||||
console.error("connection lost");
|
||||
return;
|
||||
}
|
||||
// 这里是“我收到对方 answer”,因此我这端的 from/to 应该是 (to -> from)
|
||||
currentFrom.value = to;
|
||||
currentTo.value = from;
|
||||
await RTCpeerConnection.value.setRemoteDescription(new RTCSessionDescription(answer));
|
||||
await flushRemoteCandidatesIfReady();
|
||||
flushLocalCandidatesIfReady();
|
||||
}
|
||||
|
||||
export const handleCandidate = async (candidate: any) => {
|
||||
if (!RTCpeerConnection.value) return;
|
||||
// candidate 可能早到:remoteDescription 未 set 时直接 add 会失败,先缓存
|
||||
if (!RTCpeerConnection.value.remoteDescription) {
|
||||
pendingRemoteCandidates.value.push(candidate);
|
||||
return;
|
||||
}
|
||||
await RTCpeerConnection.value.addIceCandidate(new RTCIceCandidate(candidate));
|
||||
}
|
||||
|
||||
export const hangupCall = (from: number, to: number) => {
|
||||
if(from === null || to === null) return;
|
||||
if (RTCpeerConnection.value) {
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
const msg = {
|
||||
cmd: "VOICE_CALL_END",
|
||||
from: from,
|
||||
to: to,
|
||||
time: new Date().toLocaleString()
|
||||
}
|
||||
sendMessage(msg);
|
||||
oncall.clear();
|
||||
closeLocalStream(localstream.value);
|
||||
remotestream.value = null;
|
||||
pendingLocalCandidates.value = [];
|
||||
pendingRemoteCandidates.value = [];
|
||||
currentFrom.value = null;
|
||||
currentTo.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
export const denyCall = (from: number, to: number) => {
|
||||
if(from === null || to === null) return;
|
||||
const msg = {
|
||||
cmd: "VOICE_CALL_DENY",
|
||||
from: from,
|
||||
to: to,
|
||||
time: new Date().toLocaleString()
|
||||
}
|
||||
sendMessage(msg);
|
||||
oncall.clear();
|
||||
remotestream.value = null;
|
||||
pendingLocalCandidates.value = [];
|
||||
pendingRemoteCandidates.value = [];
|
||||
currentFrom.value = null;
|
||||
currentTo.value = null;
|
||||
}
|
||||
|
||||
|
||||
export const closeConnection = () => {
|
||||
if (RTCpeerConnection.value) {
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
}
|
||||
closeLocalStream(localstream.value);
|
||||
remotestream.value = null;
|
||||
pendingLocalCandidates.value = [];
|
||||
pendingRemoteCandidates.value = [];
|
||||
currentFrom.value = null;
|
||||
currentTo.value = null;
|
||||
}
|
||||
@@ -1,93 +1,115 @@
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const onCallStore = defineStore("onCall", {
|
||||
state: () => ({
|
||||
target: {
|
||||
u_id: "",
|
||||
name: "",
|
||||
avatar: ""
|
||||
},
|
||||
panel: false,
|
||||
calling: false,
|
||||
from: false,
|
||||
status: false,
|
||||
localstream: {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
},
|
||||
remotestream: {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
}
|
||||
}),
|
||||
actions: {
|
||||
setTarget(u_id, u_name, u_avatar) {
|
||||
this.target = {
|
||||
u_id: u_id,
|
||||
name: u_name,
|
||||
avatar: u_avatar
|
||||
}
|
||||
},
|
||||
panelOn() {
|
||||
this.panel = true
|
||||
},
|
||||
panelOff() {
|
||||
this.panel = false
|
||||
},
|
||||
callingOn() {
|
||||
this.calling = true
|
||||
},
|
||||
callingOff() {
|
||||
this.calling = false
|
||||
},
|
||||
fromOn() {
|
||||
this.from = true
|
||||
},
|
||||
fromOff() {
|
||||
this.from = false
|
||||
},
|
||||
statusOn() {
|
||||
this.status = true
|
||||
},
|
||||
statusOff() {
|
||||
this.status = false
|
||||
},
|
||||
setLocalStream(stream) {
|
||||
this.localstream.audioStream = stream;
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioElement.srcObject = stream;
|
||||
}
|
||||
},
|
||||
setLocalElement(element) {
|
||||
this.localstream.audioElement = element;
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioElement.srcObject = this.localstream.audioStream;
|
||||
}
|
||||
},
|
||||
setRemoteStream(stream) {
|
||||
this.remotestream.audioStream = stream;
|
||||
if (this.remotestream.audioStream) {
|
||||
this.remotestream.audioElement.srcObject = stream;
|
||||
}
|
||||
},
|
||||
setRemoteElement(element) {
|
||||
this.remotestream.audioElement = element;
|
||||
if (this.remotestream.audioStream) {
|
||||
this.remotestream.audioElement.srcObject = this.remotestream.audioStream;
|
||||
}
|
||||
},
|
||||
resetStream() {
|
||||
// 停止本地媒体流
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioStream.getTracks().forEach(track => track.stop());
|
||||
this.localstream.audioStream = null;
|
||||
}
|
||||
|
||||
// 停止远程媒体流
|
||||
if (this.remotestream.videoStream) {
|
||||
this.remotestream.videoStream.getTracks().forEach(track => track.stop());
|
||||
this.remotestream.videoStream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const onCallStore = defineStore("onCall", {
|
||||
state: () => ({
|
||||
target: {
|
||||
u_id: "",
|
||||
name: "",
|
||||
avatar: ""
|
||||
},
|
||||
panel: false,
|
||||
calling: false,
|
||||
from: false,
|
||||
status: false,
|
||||
localstream: {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
},
|
||||
remotestream: {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
}
|
||||
}),
|
||||
actions: {
|
||||
getTarget() {
|
||||
return this.target;
|
||||
},
|
||||
setTarget(u_id:number, u_name:string, u_avatar:string) {
|
||||
this.target = {
|
||||
u_id: u_id,
|
||||
name: u_name,
|
||||
avatar: u_avatar
|
||||
}
|
||||
},
|
||||
panelOn() {
|
||||
this.panel = true
|
||||
},
|
||||
panelOff() {
|
||||
this.panel = false
|
||||
},
|
||||
callingOn() {
|
||||
this.calling = true
|
||||
},
|
||||
callingOff() {
|
||||
this.calling = false
|
||||
},
|
||||
fromOn() {
|
||||
this.from = true
|
||||
},
|
||||
fromOff() {
|
||||
this.from = false
|
||||
},
|
||||
statusOn() {
|
||||
this.status = true
|
||||
},
|
||||
statusOff() {
|
||||
this.status = false
|
||||
},
|
||||
clear(){
|
||||
this.target = {
|
||||
u_id: "",
|
||||
name: "",
|
||||
avatar: ""
|
||||
}
|
||||
this.panel = false;
|
||||
this.calling = false;
|
||||
this.from = false;
|
||||
this.status = false;
|
||||
this.localstream = {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
}
|
||||
this.remotestream = {
|
||||
audioStream: null,
|
||||
audioElement: null
|
||||
}
|
||||
},
|
||||
setLocalStream(stream) {
|
||||
this.localstream.audioStream = stream;
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioElement.srcObject = stream;
|
||||
}
|
||||
},
|
||||
setLocalElement(element) {
|
||||
this.localstream.audioElement = element;
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioElement.srcObject = this.localstream.audioStream;
|
||||
}
|
||||
},
|
||||
setRemoteStream(stream) {
|
||||
this.remotestream.audioStream = stream;
|
||||
if (this.remotestream.audioStream) {
|
||||
this.remotestream.audioElement.srcObject = stream;
|
||||
}
|
||||
},
|
||||
setRemoteElement(element) {
|
||||
this.remotestream.audioElement = element;
|
||||
if (this.remotestream.audioStream) {
|
||||
this.remotestream.audioElement.srcObject = this.remotestream.audioStream;
|
||||
}
|
||||
},
|
||||
resetStream() {
|
||||
// 停止本地媒体流
|
||||
if (this.localstream.audioStream) {
|
||||
this.localstream.audioStream.getTracks().forEach(track => track.stop());
|
||||
this.localstream.audioStream = null;
|
||||
}
|
||||
|
||||
// 停止远程媒体流
|
||||
if (this.remotestream.videoStream) {
|
||||
this.remotestream.videoStream.getTracks().forEach(track => track.stop());
|
||||
this.remotestream.videoStream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,402 +1,410 @@
|
||||
<template>
|
||||
<el-row class="container">
|
||||
<el-col :span="6">
|
||||
<el-button type="primary" @click="dialogVisibleFriendManage = true">好友管理</el-button>
|
||||
<el-input v-model="tempsearch" :prefix-icon="Search" style="width: 90%;" clearable></el-input>
|
||||
<el-scrollbar style="height: 500px;width: 90%;">
|
||||
<ul class="infinitelist" style="overflow: auto">
|
||||
<li v-for="(item) in tempsearchResult" :key="item.id" class="infinitelistitem"
|
||||
@click="switchTemplate(item.id, item.u_name, item.u_avatar)"
|
||||
:class="{ 'selected': selectedFriendId === item.id }">
|
||||
<div class="user-profile">
|
||||
<img :src="item.u_avatar" alt="User Avatar" />
|
||||
<div :class="['status-dot', statusClass]"></div>
|
||||
</div>
|
||||
<div style="display: inline-block;">{{ item.u_name }}#{{ item.u_id }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
</el-scrollbar>
|
||||
</el-col>
|
||||
<el-col :span="18">
|
||||
<el-row class="messagebox">
|
||||
<el-scrollbar ref="scrollbarRef" style="width: 100%;height: 100%;">
|
||||
<!-- 聊天消息指示框 头像、时间、内容 -->
|
||||
<div v-for="(item) in messagebox" class="message-item">
|
||||
<div
|
||||
:class="{ 'message-item-profile': true, 'left': item.from !== userinfo.user.id, 'right': item.from === userinfo.user.id }">
|
||||
<img :src="item.from !== userinfo.user.id ? oppositeAvatar : userinfo.user.u_avatar"
|
||||
alt="User Avatar" />
|
||||
</div>
|
||||
<div
|
||||
:class="{ 'message-item-content': true, 'left': item.from !== userinfo.user.id, 'right': item.from === userinfo.user.id }">
|
||||
{{ item.content }}</div>
|
||||
<div
|
||||
:class="{ 'message-item-time': true, 'left': item.from === userinfo.user.id, 'right': item.from !== userinfo.user.id }">
|
||||
{{ item.time }}</div>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
</el-row>
|
||||
<el-row>
|
||||
<el-input class="inputbox" v-model="inputValue" :placeholder="placeholder" @keyup.enter="handleEnter" clearable
|
||||
:disabled="inputDisabled"></el-input>
|
||||
<el-button class="call" :disabled="inputDisabled" @click="confirmCall()">语音通话</el-button>
|
||||
</el-row>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<!-- 确认通话弹窗 -->
|
||||
<el-dialog v-model="dialogVisibleCallConfirm" title="确认通话对象" width="30%" :before-close="handleClose">
|
||||
<el-row style="height: 80px;align-items: center;">
|
||||
<div class="user-profile">
|
||||
<img :src="oppositeAvatar" alt="User Avatar" />
|
||||
</div>
|
||||
<div>{{ oppositeName }}</div>
|
||||
</el-row>
|
||||
<el-row>
|
||||
<el-button type="primary" @click="handleConfirmCall()" style="margin: auto;">确认</el-button>
|
||||
</el-row>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 好友管理弹窗 -->
|
||||
<el-dialog v-model="dialogVisibleFriendManage" title="好友管理" style="width: 850px;height: 500px;">
|
||||
<el-input v-model="friendSearch" placeholder="搜索好友" style="margin-bottom: 10px;width: 100%;"></el-input>
|
||||
<el-table :data="friendSearchResult" style="width: 100%;height: 400px;">
|
||||
<el-table-column prop="u_avatar" label="" width="100">
|
||||
<template #default="scope">
|
||||
<!-- 使用 el-avatar 组件显示头像 -->
|
||||
<el-avatar :src="friendSearchResult[scope.$index].u_avatar" size="large" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="u_name" label="姓名" width="100"></el-table-column>
|
||||
<!-- <el-table-column prop="id" label="id" width="0"></el-table-column> -->
|
||||
<el-table-column prop="u_id" label="u_id" width="100"></el-table-column>
|
||||
<el-table-column prop="u_introduction" label="个性签名" width="200"></el-table-column>
|
||||
<el-table-column>
|
||||
<template #default="scope">
|
||||
<el-button @click="deleteChatHisory(scope.row.u_id)">删除聊天记录</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column>
|
||||
<template #default="scope">
|
||||
<el-button @click="deletefriend(scope.row.id)">删除好友</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
</el-table>
|
||||
</el-dialog>
|
||||
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, nextTick, watch, computed } from 'vue'
|
||||
import { userInfoStore } from '@/store/user';
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { onlineSocketStore } from '@/store/Online';
|
||||
import { messageStore } from '@/store/message.ts';
|
||||
import { Search } from '@element-plus/icons-vue'
|
||||
import { voiceStore } from '@/store/Voice';
|
||||
import { onCallStore } from '@/store/VoiceTarget';
|
||||
import { getFriends, deleteFriend } from '@/api/friend';
|
||||
|
||||
const socket = onlineSocketStore()
|
||||
const userinfo = userInfoStore()
|
||||
const message = messageStore()
|
||||
const voice = voiceStore()
|
||||
const oncall = onCallStore()
|
||||
|
||||
const messagebox = ref([])
|
||||
const scrollbarRef = ref(null)
|
||||
const dialogVisibleFriendManage = ref(false)
|
||||
const dialogVisibleCallConfirm = ref(false)
|
||||
|
||||
const tempsearch = ref('')
|
||||
const inputValue = ref('')
|
||||
const statusClass = ref('online')
|
||||
const inputDisabled = ref(true)
|
||||
const placeholder = ref('请选择聊天对象')
|
||||
const oppositeId = ref('')
|
||||
const oppositeName = ref('')
|
||||
const oppositeAvatar = ref('')
|
||||
|
||||
const friends = ref([])
|
||||
const friendSearch = ref('')
|
||||
const selectedFriendId = ref('')
|
||||
|
||||
const tempsearchResult = computed(() => {
|
||||
if (!tempsearch.value)
|
||||
return friends.value
|
||||
friends.value.filter(item => item.u_name.includes(tempsearch.value))
|
||||
})
|
||||
|
||||
const friendSearchResult = computed(() => {
|
||||
if (!friendSearch.value)
|
||||
return friends.value
|
||||
else
|
||||
return friends.value.filter(item => item.u_name.includes(friendSearch.value))
|
||||
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
//切换聊天对象
|
||||
const switchTemplate = (id, u_name, u_avatar) => {
|
||||
message.from = id
|
||||
oppositeId.value = id
|
||||
oppositeName.value = u_name
|
||||
oppositeAvatar.value = u_avatar
|
||||
message.setCorresponding()
|
||||
messagebox.value = message.corresponding
|
||||
inputDisabled.value = false
|
||||
placeholder.value = '请输入消息内容'
|
||||
scrollToBottom()
|
||||
selectedFriendId.value = id
|
||||
console.log(message.corresponding)
|
||||
}
|
||||
|
||||
// 定义回车键的处理函数
|
||||
const handleEnter = () => {
|
||||
if (inputValue.value === '') {
|
||||
ElMessage.error('消息不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
// 发送一类消息给目标用户
|
||||
const msg = {
|
||||
cmd: "MESSAGE",
|
||||
from: userinfo.user.id,
|
||||
to: message.from,
|
||||
content: inputValue.value,
|
||||
time: new Date().toLocaleString()
|
||||
};
|
||||
|
||||
socket.send(msg)
|
||||
message.addMessage(msg)
|
||||
inputValue.value = ''
|
||||
scrollToBottom()
|
||||
};
|
||||
|
||||
const scrollToBottom = () => {
|
||||
nextTick(() => {
|
||||
const scrollbar = scrollbarRef.value?.$el; // 获取 el-scrollbar 的根元素
|
||||
if (scrollbar) {
|
||||
const scrollWrap = scrollbar.querySelector(".el-scrollbar__wrap"); // 找到滚动区域
|
||||
if (scrollWrap) {
|
||||
scrollWrap.scrollTop = scrollWrap.scrollHeight; // 滚动到底部
|
||||
} else {
|
||||
console.error("滚动容器未找到,请检查 el-scrollbar 的 DOM 结构");
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 监听消息
|
||||
watch(() => message.messages.length, (newLength, oldLength) => {
|
||||
const msg = message.messages[newLength - 1]
|
||||
console.log("监听到新消息:", msg)
|
||||
if (newLength > oldLength && (msg.from === message.from && msg.to === message.to) || (msg.from === message.to && msg.to === message.from)) {
|
||||
messagebox.value.push(msg)
|
||||
scrollToBottom()
|
||||
}
|
||||
})
|
||||
|
||||
const deletefriend = (id) => {
|
||||
if(deleteFriend(id)){
|
||||
inputValue.value = ''
|
||||
inputDisabled.value = true
|
||||
placeholder.value = '请选择聊天对象'
|
||||
oppositeAvatar.value = ''
|
||||
ElMessage.success('删除好友成功')
|
||||
friends.value = getFriends()
|
||||
return
|
||||
}else{
|
||||
ElMessage.error('删除好友失败')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const deleteChatHisory = (u_id) => {
|
||||
try {
|
||||
if (u_id === message.sender) messagebox.value = []
|
||||
message.deleteMessagesHistory(userinfo.user.u_id, u_id)
|
||||
} catch (e) {
|
||||
ElMessage.error('删除聊天记录失败')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCall = () => {
|
||||
dialogVisibleCallConfirm.value = true
|
||||
}
|
||||
|
||||
const handleConfirmCall = () => {
|
||||
dialogVisibleCallConfirm.value = false
|
||||
oncall.setTarget(oppositeId.value, oppositeName.value, oppositeAvatar.value)
|
||||
oncall.panelOn()
|
||||
oncall.callingOn()
|
||||
oncall.fromOn()
|
||||
voice.startCall(userinfo.user.u_id, userinfo.user.u_name, userinfo.user.u_avatar, oppositeId.value)
|
||||
}
|
||||
|
||||
|
||||
onMounted(async () => {
|
||||
friends.value = await getFriends()
|
||||
await nextTick()
|
||||
console.log(friends.value)
|
||||
console.log(message.from)
|
||||
if (message.from !== '' || message.from !== null) {
|
||||
console.log("切换聊天对象")
|
||||
const foundUser = friends.value.find((friend) => friend.id === message.from);
|
||||
switchTemplate(message.from, foundUser.u_name, foundUser.u_avatar)
|
||||
}
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.container {
|
||||
height: 70%;
|
||||
margin-top: 4%;
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.infinitelist {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.infinitelistitem {
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.infinitelistitem.selected {
|
||||
background-color: #f0f0f0;
|
||||
/* 灰色背景 */
|
||||
}
|
||||
|
||||
.messagebox {
|
||||
height: 400px;
|
||||
border: 1px solid #cccccc;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.inputbox {
|
||||
margin-top: 10px;
|
||||
margin-left: 10px;
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.user-profile-link {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
/* 去掉链接的下划线 */
|
||||
}
|
||||
|
||||
.user-profile {
|
||||
position: relative;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
|
||||
}
|
||||
|
||||
.user-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
position: absolute;
|
||||
bottom: -5px;
|
||||
right: -5px;
|
||||
z-index: 1;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.online {
|
||||
background-color: green;
|
||||
/* 在线状态 */
|
||||
}
|
||||
|
||||
.offline {
|
||||
background-color: red;
|
||||
/* 离线状态 */
|
||||
}
|
||||
|
||||
.message-item {
|
||||
padding: 10px;
|
||||
height: 80px;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.message-item-profile {
|
||||
position: absolute;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.message-item-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.message-item-profile.left {
|
||||
left: 20px;
|
||||
}
|
||||
|
||||
.message-item-profile.right {
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.message-item-content {
|
||||
position: absolute;
|
||||
display: inline-block;
|
||||
bottom: 28px;
|
||||
}
|
||||
|
||||
.message-item-content.left {
|
||||
left: 90px;
|
||||
}
|
||||
|
||||
.message-item-content.right {
|
||||
right: 90px;
|
||||
}
|
||||
|
||||
.message-item-time {
|
||||
position: absolute;
|
||||
bottom: 23px;
|
||||
height: 20px;
|
||||
text-align: left;
|
||||
font-size: small;
|
||||
}
|
||||
|
||||
.message-item-time.left {
|
||||
left: 20px;
|
||||
}
|
||||
|
||||
.message-item-time.right {
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.call {
|
||||
margin: auto;
|
||||
margin-top: 10px;
|
||||
}
|
||||
<template>
|
||||
<el-row class="container">
|
||||
<el-col :span="6">
|
||||
<el-button type="primary" @click="dialogVisibleFriendManage = true">好友管理</el-button>
|
||||
<el-input v-model="tempsearch" :prefix-icon="Search" style="width: 90%;" clearable></el-input>
|
||||
<el-scrollbar style="height: 500px;width: 90%;">
|
||||
<ul class="infinitelist" style="overflow: auto">
|
||||
<li v-for="(item) in tempsearchResult" :key="item.id" class="infinitelistitem"
|
||||
@click="switchTemplate(item.id, item.u_name, item.u_avatar)"
|
||||
:class="{ 'selected': selectedFriendId === item.id }">
|
||||
<div class="user-profile">
|
||||
<img :src="item.u_avatar" alt="User Avatar" />
|
||||
<div :class="['status-dot', statusClass]"></div>
|
||||
</div>
|
||||
<div style="display: inline-block;">{{ item.u_name }}#{{ item.u_id }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
</el-scrollbar>
|
||||
</el-col>
|
||||
<el-col :span="18">
|
||||
<el-row class="messagebox">
|
||||
<el-scrollbar ref="scrollbarRef" style="width: 100%;height: 100%;">
|
||||
<!-- 聊天消息指示框 头像、时间、内容 -->
|
||||
<div v-for="(item) in messagebox" class="message-item">
|
||||
<div
|
||||
:class="{ 'message-item-profile': true, 'left': item.from !== userinfo.user.id, 'right': item.from === userinfo.user.id }">
|
||||
<img :src="item.from !== userinfo.user.id ? oppositeAvatar : userinfo.user.u_avatar"
|
||||
alt="User Avatar" />
|
||||
</div>
|
||||
<div
|
||||
:class="{ 'message-item-content': true, 'left': item.from !== userinfo.user.id, 'right': item.from === userinfo.user.id }">
|
||||
{{ item.content }}</div>
|
||||
<div
|
||||
:class="{ 'message-item-time': true, 'left': item.from === userinfo.user.id, 'right': item.from !== userinfo.user.id }">
|
||||
{{ item.time }}</div>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
</el-row>
|
||||
<el-row>
|
||||
<el-input class="inputbox" v-model="inputValue" :placeholder="placeholder" @keyup.enter="handleEnter" clearable
|
||||
:disabled="inputDisabled"></el-input>
|
||||
<el-button class="call" :disabled="inputDisabled" @click="confirmCall()">语音通话</el-button>
|
||||
</el-row>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<!-- 确认通话弹窗 -->
|
||||
<el-dialog v-model="dialogVisibleCallConfirm" title="确认通话对象" width="30%" :before-close="handleClose">
|
||||
<el-row style="height: 80px;align-items: center;">
|
||||
<div class="user-profile">
|
||||
<img :src="oppositeAvatar" alt="User Avatar" />
|
||||
</div>
|
||||
<div>{{ oppositeName }}</div>
|
||||
</el-row>
|
||||
<el-row>
|
||||
<el-button type="primary" @click="handleConfirmCall()" style="margin: auto;">确认</el-button>
|
||||
</el-row>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 好友管理弹窗 -->
|
||||
<el-dialog v-model="dialogVisibleFriendManage" title="好友管理" style="width: 850px;height: 500px;">
|
||||
<el-input v-model="friendSearch" placeholder="搜索好友" style="margin-bottom: 10px;width: 100%;"></el-input>
|
||||
<el-table :data="friendSearchResult" style="width: 100%;height: 400px;">
|
||||
<el-table-column prop="u_avatar" label="" width="100">
|
||||
<template #default="scope">
|
||||
<!-- 使用 el-avatar 组件显示头像 -->
|
||||
<el-avatar :src="friendSearchResult[scope.$index].u_avatar" size="large" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="u_name" label="姓名" width="100"></el-table-column>
|
||||
<!-- <el-table-column prop="id" label="id" width="0"></el-table-column> -->
|
||||
<el-table-column prop="u_id" label="u_id" width="100"></el-table-column>
|
||||
<el-table-column prop="u_introduction" label="个性签名" width="200"></el-table-column>
|
||||
<el-table-column>
|
||||
<template #default="scope">
|
||||
<el-button @click="deleteChatHisory(scope.row.u_id)">删除聊天记录</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column>
|
||||
<template #default="scope">
|
||||
<el-button @click="deletefriend(scope.row.id)">删除好友</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
</el-table>
|
||||
</el-dialog>
|
||||
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, nextTick, watch, computed } from 'vue'
|
||||
import { userInfoStore } from '@/store/user';
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { sendMessage } from '@/websocket/onlineSocket';
|
||||
import { messageStore } from '@/store/message.ts';
|
||||
import { Search } from '@element-plus/icons-vue'
|
||||
import { onCallStore } from '@/store/VoiceTarget.ts';
|
||||
import { getFriends, deleteFriend } from '@/api/friend';
|
||||
|
||||
|
||||
const userinfo = userInfoStore()
|
||||
const message = messageStore()
|
||||
const oncall = onCallStore()
|
||||
|
||||
const messagebox = ref([])
|
||||
const scrollbarRef = ref(null)
|
||||
const dialogVisibleFriendManage = ref(false)
|
||||
const dialogVisibleCallConfirm = ref(false)
|
||||
|
||||
const tempsearch = ref('')
|
||||
const inputValue = ref('')
|
||||
const statusClass = ref('online')
|
||||
const inputDisabled = ref(true)
|
||||
const placeholder = ref('请选择聊天对象')
|
||||
const oppositeId = ref('')
|
||||
const oppositeName = ref('')
|
||||
const oppositeAvatar = ref('')
|
||||
|
||||
const friends = ref([])
|
||||
const friendSearch = ref('')
|
||||
const selectedFriendId = ref('')
|
||||
|
||||
const tempsearchResult = computed(() => {
|
||||
if (!tempsearch.value)
|
||||
return friends.value
|
||||
else
|
||||
return friends.value.filter(item => item.u_name.includes(tempsearch.value))
|
||||
})
|
||||
|
||||
const friendSearchResult = computed(() => {
|
||||
if (!friendSearch.value)
|
||||
return friends.value
|
||||
else
|
||||
return friends.value.filter(item => item.u_name.includes(friendSearch.value))
|
||||
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
//切换聊天对象
|
||||
const switchTemplate = (id, u_name, u_avatar) => {
|
||||
message.from = id
|
||||
oppositeId.value = id
|
||||
oppositeName.value = u_name
|
||||
oppositeAvatar.value = u_avatar
|
||||
message.setCorresponding()
|
||||
messagebox.value = message.corresponding
|
||||
inputDisabled.value = false
|
||||
placeholder.value = '请输入消息内容'
|
||||
scrollToBottom()
|
||||
selectedFriendId.value = id
|
||||
console.log(message.corresponding)
|
||||
}
|
||||
|
||||
// 定义回车键的处理函数
|
||||
const handleEnter = () => {
|
||||
if (inputValue.value === '') {
|
||||
ElMessage.error('消息不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
// 发送一类消息给目标用户
|
||||
const msg = {
|
||||
cmd: "MESSAGE",
|
||||
from: userinfo.user.id,
|
||||
to: message.from,
|
||||
content: inputValue.value,
|
||||
time: new Date().toLocaleString()
|
||||
};
|
||||
|
||||
sendMessage(msg);
|
||||
message.addMessage(msg)
|
||||
inputValue.value = ''
|
||||
scrollToBottom()
|
||||
};
|
||||
|
||||
const scrollToBottom = () => {
|
||||
nextTick(() => {
|
||||
const scrollbar = scrollbarRef.value?.$el; // 获取 el-scrollbar 的根元素
|
||||
if (scrollbar) {
|
||||
const scrollWrap = scrollbar.querySelector(".el-scrollbar__wrap"); // 找到滚动区域
|
||||
if (scrollWrap) {
|
||||
scrollWrap.scrollTop = scrollWrap.scrollHeight; // 滚动到底部
|
||||
} else {
|
||||
console.error("滚动容器未找到,请检查 el-scrollbar 的 DOM 结构");
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 监听消息
|
||||
watch(() => message.messages.length, (newLength, oldLength) => {
|
||||
const msg = message.messages[newLength - 1]
|
||||
console.log("监听到新消息:", msg)
|
||||
if (newLength > oldLength && (msg.from === message.from && msg.to === message.to) || (msg.from === message.to && msg.to === message.from)) {
|
||||
messagebox.value.push(msg)
|
||||
scrollToBottom()
|
||||
}
|
||||
})
|
||||
|
||||
const deletefriend = (id) => {
|
||||
if(deleteFriend(id)){
|
||||
inputValue.value = ''
|
||||
inputDisabled.value = true
|
||||
placeholder.value = '请选择聊天对象'
|
||||
oppositeAvatar.value = ''
|
||||
ElMessage.success('删除好友成功')
|
||||
friends.value = getFriends()
|
||||
return
|
||||
}else{
|
||||
ElMessage.error('删除好友失败')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const deleteChatHisory = (u_id) => {
|
||||
try {
|
||||
if (u_id === message.sender) messagebox.value = []
|
||||
message.deleteMessagesHistory(userinfo.user.u_id, u_id)
|
||||
} catch (e) {
|
||||
ElMessage.error('删除聊天记录失败')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCall = () => {
|
||||
dialogVisibleCallConfirm.value = true
|
||||
}
|
||||
|
||||
const handleConfirmCall = () => {
|
||||
dialogVisibleCallConfirm.value = false
|
||||
oncall.setTarget(oppositeId.value, oppositeName.value, oppositeAvatar.value)
|
||||
oncall.panelOn()
|
||||
oncall.callingOn()
|
||||
oncall.fromOn()
|
||||
// voice.startCall(userinfo.user.u_id, userinfo.user.u_name, userinfo.user.u_avatar, oppositeId.value)
|
||||
const msg = {
|
||||
cmd: "VOICE_CALL_REQUEST",
|
||||
from: userinfo.user.id,
|
||||
from_name: userinfo.user.u_name,
|
||||
from_avatar: userinfo.user.u_avatar,
|
||||
to: oppositeId.value,
|
||||
time: new Date().toLocaleString()
|
||||
}
|
||||
sendMessage(msg);
|
||||
}
|
||||
|
||||
|
||||
onMounted(async () => {
|
||||
friends.value = await getFriends()
|
||||
await nextTick()
|
||||
console.log(friends.value)
|
||||
console.log(message.from)
|
||||
if (message.from !== '' || message.from !== null) {
|
||||
console.log("切换聊天对象")
|
||||
const foundUser = friends.value.find((friend) => friend.id === message.from);
|
||||
switchTemplate(message.from, foundUser.u_name, foundUser.u_avatar)
|
||||
}
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.container {
|
||||
height: 70%;
|
||||
margin-top: 4%;
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.infinitelist {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.infinitelistitem {
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.infinitelistitem.selected {
|
||||
background-color: #f0f0f0;
|
||||
/* 灰色背景 */
|
||||
}
|
||||
|
||||
.messagebox {
|
||||
height: 400px;
|
||||
border: 1px solid #cccccc;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.inputbox {
|
||||
margin-top: 10px;
|
||||
margin-left: 10px;
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.user-profile-link {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
/* 去掉链接的下划线 */
|
||||
}
|
||||
|
||||
.user-profile {
|
||||
position: relative;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
|
||||
}
|
||||
|
||||
.user-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
position: absolute;
|
||||
bottom: -5px;
|
||||
right: -5px;
|
||||
z-index: 1;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.online {
|
||||
background-color: green;
|
||||
/* 在线状态 */
|
||||
}
|
||||
|
||||
.offline {
|
||||
background-color: red;
|
||||
/* 离线状态 */
|
||||
}
|
||||
|
||||
.message-item {
|
||||
padding: 10px;
|
||||
height: 80px;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.message-item-profile {
|
||||
position: absolute;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.message-item-profile img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.message-item-profile.left {
|
||||
left: 20px;
|
||||
}
|
||||
|
||||
.message-item-profile.right {
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.message-item-content {
|
||||
position: absolute;
|
||||
display: inline-block;
|
||||
bottom: 28px;
|
||||
}
|
||||
|
||||
.message-item-content.left {
|
||||
left: 90px;
|
||||
}
|
||||
|
||||
.message-item-content.right {
|
||||
right: 90px;
|
||||
}
|
||||
|
||||
.message-item-time {
|
||||
position: absolute;
|
||||
bottom: 23px;
|
||||
height: 20px;
|
||||
text-align: left;
|
||||
font-size: small;
|
||||
}
|
||||
|
||||
.message-item-time.left {
|
||||
left: 20px;
|
||||
}
|
||||
|
||||
.message-item-time.right {
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.call {
|
||||
margin: auto;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,88 +1,85 @@
|
||||
<template>
|
||||
<!-- 顶部导航栏 -->
|
||||
<Navbar />
|
||||
|
||||
<div class="home-container">
|
||||
|
||||
|
||||
<div id="mainContent" class="main-content">
|
||||
<!-- 左侧主空间 -->
|
||||
<div class="left-content">
|
||||
<router-view />
|
||||
</div>
|
||||
</div>
|
||||
<!-- 语音面板 -->
|
||||
<phonePanel />
|
||||
|
||||
<!-- 消息按钮 -->
|
||||
<GlobalMessageButton />
|
||||
|
||||
<!-- 右下角用户头像框 -->
|
||||
<UserProfile />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, watchEffect } from 'vue';
|
||||
import Navbar from '../../components/navBar.vue';
|
||||
import UserProfile from '../../components/userProfile.vue';
|
||||
import { userInfoStore } from '@/store/user';
|
||||
import { onlineSocketStore } from '@/store/Online';
|
||||
import { getUserInfo } from '@/api/user';
|
||||
import GlobalMessageButton from '@/components/GlobalMessageButton.vue';
|
||||
import { messageStore } from '@/store/message.ts';
|
||||
import phonePanel from '@/components/phonePanel.vue';
|
||||
import { voiceStore } from '@/store/Voice';
|
||||
import { initDB } from '@/functions/historyMessages';
|
||||
|
||||
const voice = voiceStore();
|
||||
|
||||
const userinfo = userInfoStore();
|
||||
const socket = onlineSocketStore();
|
||||
const message = messageStore();
|
||||
|
||||
onMounted(() => {
|
||||
getUserInfo()
|
||||
|
||||
// 使用 watchEffect 监听 u_id 是否为空
|
||||
watchEffect(() => {
|
||||
if (userinfo.user.u_id) { // 如果 u_id 不为空
|
||||
console.log('User ID is available:', userinfo.user.u_id);
|
||||
socket.connect(userinfo.user.id); // 建立 WebSocket 连接
|
||||
message.to = userinfo.user.id; // 设置消息发送者为当前用户 ID
|
||||
|
||||
// voice.connect(userinfo.user.u_id); // 建立语音通话连接
|
||||
}
|
||||
});
|
||||
|
||||
initDB(); // 初始化历史消息数据库
|
||||
})
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.home-container {
|
||||
position: relative;
|
||||
top: 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
position: relative;
|
||||
left: 0;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
margin-top: 72px;
|
||||
|
||||
}
|
||||
|
||||
.left-content {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
}
|
||||
<template>
|
||||
<!-- 顶部导航栏 -->
|
||||
<Navbar />
|
||||
|
||||
<div class="home-container">
|
||||
|
||||
|
||||
<div id="mainContent" class="main-content">
|
||||
<!-- 左侧主空间 -->
|
||||
<div class="left-content">
|
||||
<router-view />
|
||||
</div>
|
||||
</div>
|
||||
<!-- 语音面板 -->
|
||||
<phonePanel />
|
||||
|
||||
<!-- 消息按钮 -->
|
||||
<GlobalMessageButton />
|
||||
|
||||
<!-- 右下角用户头像框 -->
|
||||
<UserProfile />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, watchEffect } from 'vue';
|
||||
import Navbar from '../../components/navBar.vue';
|
||||
import UserProfile from '../../components/userProfile.vue';
|
||||
import { userInfoStore } from '@/store/user';
|
||||
import { onlineSocketStore } from '@/store/Online.ts';
|
||||
import { getUserInfo } from '@/api/user';
|
||||
import GlobalMessageButton from '@/components/GlobalMessageButton.vue';
|
||||
import { messageStore } from '@/store/message.ts';
|
||||
import phonePanel from '@/components/phonePanel.vue';
|
||||
import { initDB } from '@/functions/historyMessages';
|
||||
|
||||
const userinfo = userInfoStore();
|
||||
const socket = onlineSocketStore();
|
||||
const message = messageStore();
|
||||
|
||||
onMounted(() => {
|
||||
getUserInfo()
|
||||
|
||||
// 使用 watchEffect 监听 u_id 是否为空
|
||||
watchEffect(() => {
|
||||
if (userinfo.user.u_id) { // 如果 u_id 不为空
|
||||
console.log('User ID is available:', userinfo.user.u_id);
|
||||
socket.connect(userinfo.user.id); // 建立 WebSocket 连接
|
||||
message.to = userinfo.user.id; // 设置消息发送者为当前用户 ID
|
||||
|
||||
// voice.connect(userinfo.user.u_id); // 建立语音通话连接
|
||||
}
|
||||
});
|
||||
|
||||
initDB(); // 初始化历史消息数据库
|
||||
})
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.home-container {
|
||||
position: relative;
|
||||
top: 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
position: relative;
|
||||
left: 0;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
margin-top: 72px;
|
||||
|
||||
}
|
||||
|
||||
.left-content {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,191 +1,218 @@
|
||||
import { ref } from "vue";
|
||||
import { userInfoStore } from "@/store/user";
|
||||
import { messageStore } from "@/store/message";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { messageSignStore } from "@/store/message_sign";
|
||||
import { groupMessageStore } from "@/store/group_message";
|
||||
|
||||
// userinfo 实例
|
||||
const userinfo = userInfoStore();
|
||||
// message 实例
|
||||
const message = messageStore();
|
||||
// groupMessage 实例
|
||||
const groupMessage = groupMessageStore();
|
||||
// messageSignStoregn 实例
|
||||
// const messageSign = messageSignStore();
|
||||
|
||||
// WebSocket 实例
|
||||
const socket = ref(null);
|
||||
const messageSign = messageSignStore();
|
||||
|
||||
const isManualClose = ref(false);
|
||||
|
||||
const reconnectScheduled = ref(false);
|
||||
|
||||
const retryCount = ref(0);
|
||||
|
||||
export const getRetryCount = () => {
|
||||
return retryCount.value;
|
||||
};
|
||||
|
||||
export const addRetryCount = () => {
|
||||
retryCount.value = retryCount.value + 1;
|
||||
};
|
||||
|
||||
export const resetRetryCount = () => {
|
||||
retryCount.value = 0;
|
||||
};
|
||||
export const setReconnectScheduled = (value) => {
|
||||
reconnectScheduled.value = value;
|
||||
};
|
||||
|
||||
export const getReconnectScheduled = () => {
|
||||
return reconnectScheduled.value;
|
||||
};
|
||||
|
||||
export const setIsManualClose = (value) => {
|
||||
isManualClose.value = value;
|
||||
};
|
||||
|
||||
export const getIsManualClose = () => {
|
||||
return isManualClose.value;
|
||||
};
|
||||
|
||||
// 连接WebSocket
|
||||
export const connectWebSocket = () => {
|
||||
const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
|
||||
const host = window.location.host;
|
||||
const socketUrl = `${protocol}${host}/ws/online?name=${userinfo.user.u_name}`;
|
||||
|
||||
// const socketUrl = `ws://localhost:8080/online?u_id=${userinfo.user.u_id}&u_name=${userinfo.user.u_name}`;
|
||||
if (socket.value && socket.value.readyState !== WebSocket.CLOSED) {
|
||||
console.log("还在重连中...");
|
||||
return;
|
||||
}
|
||||
const retrytime = getRetryCount();
|
||||
if (retrytime >= 10) {
|
||||
console.log("重连失败,请稍后再试");
|
||||
return;
|
||||
}
|
||||
console.log(retrytime);
|
||||
socket.value = new WebSocket(socketUrl, "token-"+ userinfo.token);
|
||||
|
||||
socket.value.onopen = (event) => {
|
||||
console.log("WebSocket连接已建立", event);
|
||||
setReconnectScheduled(false);
|
||||
setIsManualClose(false);
|
||||
resetRetryCount();
|
||||
};
|
||||
|
||||
//处理消息逻辑
|
||||
socket.value.onmessage = (event) => {
|
||||
console.log("从服务器收到消息:", event.data);
|
||||
try{
|
||||
const MessageData = JSON.parse(event.data);
|
||||
const cmd = MessageData.cmd;
|
||||
switch(cmd){
|
||||
case "MESSAGE":
|
||||
message.addMessage(MessageData);
|
||||
// TODO:需要使用u_name或者u_id进行消息标记
|
||||
// messageSign.setMessageSign(true);
|
||||
// ElMessage.info("您有一条新的消息");
|
||||
break;
|
||||
case "PERSONAL_NOTIFY":
|
||||
messageSign.setMessageSign(true);
|
||||
ElMessage.info("您有一条新的邀请消息");
|
||||
break;
|
||||
case "GROUP_MESSAGE":
|
||||
groupMessage.recieveMessage(userinfo.user.id, MessageData);
|
||||
|
||||
// TODO: 需要使用groupId进行消息标记
|
||||
break;
|
||||
case "VIDEO_SYNC":
|
||||
console.log("视频同步消息", MessageData);
|
||||
break;
|
||||
|
||||
// 语音通话相关:
|
||||
case "VOICE_CALL_REQUEST":
|
||||
ElMessage.info("您有一个新的语音通话请求");
|
||||
break;
|
||||
case "VOICE_CALL_RESPONSE":
|
||||
console.log("收到语音通话响应消息");
|
||||
break;
|
||||
case "VOICE_CALL_DENY":
|
||||
ElMessage.info("对方拒绝了您的语音通话请求");
|
||||
break;
|
||||
case "VOICE_CALL_END":
|
||||
ElMessage.info("语音通话已结束");
|
||||
break;
|
||||
case "VOICE_ICE_CANDIDATE":
|
||||
console.log("收到新的ICE候选", MessageData.candidate);
|
||||
break;
|
||||
case "VOICE_SDP_OFFER":
|
||||
console.log("收到SDP Offer", MessageData.sdp);
|
||||
break;
|
||||
case "VOICE_SDP_ANSWER":
|
||||
console.log("收到SDP Answer", MessageData.sdp);
|
||||
break;
|
||||
|
||||
}
|
||||
}catch(error){
|
||||
console.error("解析 JSON 失败:", error);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
socket.value.onerror = (error) => {
|
||||
console.error("WebSocket发生错误:", error);
|
||||
// console.log(error);
|
||||
setReconnectScheduled(true);
|
||||
socket.value.close();
|
||||
};
|
||||
|
||||
socket.value.onclose = (event) => {
|
||||
message.saveMessagesHistory(userinfo.user.id);
|
||||
if (!getIsManualClose()) {
|
||||
if (getReconnectScheduled()) {
|
||||
socket.value = null;
|
||||
addRetryCount();
|
||||
setTimeout(reConnectWebSocket, 5000);
|
||||
setReconnectScheduled(false);
|
||||
} else {
|
||||
// console.log("websocket因为浏览器省电设置断开");
|
||||
console.log("WebSocket连接已关闭", event);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// 断开WebSocket连接
|
||||
export const disconnectWebSocket = () => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.close();
|
||||
}
|
||||
};
|
||||
|
||||
// 重连机制
|
||||
export const reConnectWebSocket = () => {
|
||||
connectWebSocket();
|
||||
};
|
||||
|
||||
// 发送消息
|
||||
export const sendMessage = (message) => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.send(message);
|
||||
} else {
|
||||
console.warn("WebSocket未连接,无法发送消息");
|
||||
}
|
||||
};
|
||||
|
||||
//没有错误的重连,只是浏览器在后台断开了连接
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
} else {
|
||||
if (!getIsManualClose() && socket.value.readyState === WebSocket.CLOSED) {
|
||||
if (getReconnectScheduled()) {
|
||||
return;
|
||||
}
|
||||
reConnectWebSocket();
|
||||
}
|
||||
}
|
||||
});
|
||||
import { ref } from "vue";
|
||||
import { userInfoStore } from "@/store/user";
|
||||
import { messageStore } from "@/store/message";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { messageSignStore } from "@/store/message_sign";
|
||||
import { groupMessageStore } from "@/store/group_message";
|
||||
import { onCallStore } from "@/store/VoiceTarget";
|
||||
import { handleOffer, handleAnswer, closeConnection, handleCandidate } from "@/store/Voice.ts";
|
||||
|
||||
// userinfo 实例
|
||||
const userinfo = userInfoStore();
|
||||
// message 实例
|
||||
const message = messageStore();
|
||||
// groupMessage 实例
|
||||
const groupMessage = groupMessageStore();
|
||||
// oncall 实例
|
||||
const oncall = onCallStore();
|
||||
// messageSignStoregn 实例
|
||||
// const messageSign = messageSignStore();
|
||||
|
||||
// WebSocket 实例
|
||||
const socket = ref(null);
|
||||
const messageSign = messageSignStore();
|
||||
|
||||
const isManualClose = ref(false);
|
||||
|
||||
const reconnectScheduled = ref(false);
|
||||
|
||||
const retryCount = ref(0);
|
||||
|
||||
|
||||
export const getRetryCount = () => {
|
||||
return retryCount.value;
|
||||
};
|
||||
|
||||
export const addRetryCount = () => {
|
||||
retryCount.value = retryCount.value + 1;
|
||||
};
|
||||
|
||||
export const resetRetryCount = () => {
|
||||
retryCount.value = 0;
|
||||
};
|
||||
export const setReconnectScheduled = (value) => {
|
||||
reconnectScheduled.value = value;
|
||||
};
|
||||
|
||||
export const getReconnectScheduled = () => {
|
||||
return reconnectScheduled.value;
|
||||
};
|
||||
|
||||
export const setIsManualClose = (value) => {
|
||||
isManualClose.value = value;
|
||||
};
|
||||
|
||||
export const getIsManualClose = () => {
|
||||
return isManualClose.value;
|
||||
};
|
||||
|
||||
// 连接WebSocket
|
||||
export const connectWebSocket = () => {
|
||||
const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
|
||||
const host = window.location.host;
|
||||
const socketUrl = `${protocol}${host}/ws/online?name=${userinfo.user.u_name}`;
|
||||
|
||||
// const socketUrl = `ws://localhost:8080/online?u_id=${userinfo.user.u_id}&u_name=${userinfo.user.u_name}`;
|
||||
if (socket.value && socket.value.readyState !== WebSocket.CLOSED) {
|
||||
console.log("还在重连中...");
|
||||
return;
|
||||
}
|
||||
const retrytime = getRetryCount();
|
||||
if (retrytime >= 10) {
|
||||
console.log("重连失败,请稍后再试");
|
||||
return;
|
||||
}
|
||||
console.log(retrytime);
|
||||
socket.value = new WebSocket(socketUrl, "token-"+ userinfo.token);
|
||||
|
||||
socket.value.onopen = (event) => {
|
||||
console.log("WebSocket连接已建立", event);
|
||||
setReconnectScheduled(false);
|
||||
setIsManualClose(false);
|
||||
resetRetryCount();
|
||||
};
|
||||
|
||||
//处理消息逻辑
|
||||
socket.value.onmessage = async (event) => {
|
||||
console.log("从服务器收到消息:", event.data);
|
||||
try{
|
||||
const MessageData = JSON.parse(event.data);
|
||||
const cmd = MessageData.cmd;
|
||||
switch(cmd){
|
||||
case "MESSAGE":
|
||||
message.addMessage(MessageData);
|
||||
// TODO:需要使用u_name或者u_id进行消息标记
|
||||
// messageSign.setMessageSign(true);
|
||||
// ElMessage.info("您有一条新的消息");
|
||||
break;
|
||||
case "PERSONAL_NOTIFY":
|
||||
messageSign.setMessageSign(true);
|
||||
ElMessage.info("您有一条新的邀请消息");
|
||||
break;
|
||||
case "GROUP_MESSAGE":
|
||||
groupMessage.recieveMessage(userinfo.user.id, MessageData);
|
||||
|
||||
// TODO: 需要使用groupId进行消息标记
|
||||
break;
|
||||
case "VIDEO_SYNC":
|
||||
console.log("视频同步消息", MessageData);
|
||||
break;
|
||||
|
||||
// 语音通话相关:
|
||||
case "VOICE_CALL_REQUEST":
|
||||
ElMessage.info("您有一个新的语音通话请求");
|
||||
oncall.setTarget(MessageData.from, MessageData.from_name, MessageData.from_avatar);
|
||||
oncall.panelOn();
|
||||
oncall.callingOn();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
break;
|
||||
case "VOICE_CALL_RESPONSE":
|
||||
console.log("收到语音通话响应消息");
|
||||
//直接跳转到icecandidate阶段,不再接收额外的响应消息
|
||||
break;
|
||||
case "VOICE_CALL_DENY":
|
||||
ElMessage.info("对方拒绝了您的语音通话请求");
|
||||
oncall.clear();
|
||||
break;
|
||||
case "VOICE_CALL_END":
|
||||
ElMessage.info("语音通话已结束");
|
||||
closeConnection();
|
||||
oncall.clear();
|
||||
break;
|
||||
case "VOICE_ICE_CANDIDATE":
|
||||
// stage3 : 收到ICE候选,添加到RTC连接中
|
||||
console.log("收到新的ICE候选");
|
||||
await handleCandidate(MessageData.content);
|
||||
break;
|
||||
case "VOICE_SDP_OFFER":
|
||||
// stage1 :收到offer,发送answer
|
||||
console.log("收到SDP Offer");
|
||||
await handleOffer(MessageData.content, MessageData.from, MessageData.to);
|
||||
break;
|
||||
case "VOICE_SDP_ANSWER":
|
||||
// stage2 : 收到answer,设置远端SDP
|
||||
console.log("收到SDP Answer");
|
||||
await handleAnswer(MessageData.content, MessageData.from, MessageData.to);
|
||||
break;
|
||||
|
||||
}
|
||||
}catch(error){
|
||||
console.error("解析 JSON 失败:", error);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
socket.value.onerror = (error) => {
|
||||
console.error("WebSocket发生错误:", error);
|
||||
// console.log(error);
|
||||
setReconnectScheduled(true);
|
||||
socket.value.close();
|
||||
};
|
||||
|
||||
socket.value.onclose = (event) => {
|
||||
message.saveMessagesHistory(userinfo.user.id);
|
||||
if (!getIsManualClose()) {
|
||||
if (getReconnectScheduled()) {
|
||||
socket.value = null;
|
||||
addRetryCount();
|
||||
setTimeout(reConnectWebSocket, 5000);
|
||||
setReconnectScheduled(false);
|
||||
} else {
|
||||
// console.log("websocket因为浏览器省电设置断开");
|
||||
console.log("WebSocket连接已关闭", event);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// 断开WebSocket连接
|
||||
export const disconnectWebSocket = () => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.close();
|
||||
}
|
||||
};
|
||||
|
||||
// 重连机制
|
||||
export const reConnectWebSocket = () => {
|
||||
connectWebSocket();
|
||||
};
|
||||
|
||||
// 发送消息
|
||||
export const sendMessage = (message) => {
|
||||
try {
|
||||
const jsonmessage = JSON.stringify(message);
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.send(jsonmessage);
|
||||
} else {
|
||||
console.warn("WebSocket未连接,无法发送消息");
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error("Failed to stringify message:", error);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
//没有错误的重连,只是浏览器在后台断开了连接
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
} else {
|
||||
if (!getIsManualClose() && socket.value.readyState === WebSocket.CLOSED) {
|
||||
if (getReconnectScheduled()) {
|
||||
return;
|
||||
}
|
||||
reConnectWebSocket();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,287 +1,286 @@
|
||||
import { ref } from "vue";
|
||||
import { userInfoStore } from "@/store/user";
|
||||
import { onCallStore } from "@/store/VoiceTarget";
|
||||
import { ElMessage } from "element-plus";
|
||||
|
||||
// userinfo 实例
|
||||
const userinfo = userInfoStore();
|
||||
// oncall 实例
|
||||
const oncall = onCallStore();
|
||||
// WebSocket 实例
|
||||
const socket = ref(null);
|
||||
|
||||
const isManualClose = ref(false);
|
||||
const reconnectScheduled = ref(false);
|
||||
const retryCount = ref(0);
|
||||
|
||||
const getRetryCount = () => {
|
||||
return retryCount.value;
|
||||
};
|
||||
const addRetryCount = () => {
|
||||
retryCount.value = retryCount.value + 1;
|
||||
};
|
||||
const resetRetryCount = () => {
|
||||
retryCount.value = 0;
|
||||
};
|
||||
const setReconnectScheduled = (value) => {
|
||||
reconnectScheduled.value = value;
|
||||
};
|
||||
const getReconnectScheduled = () => {
|
||||
return reconnectScheduled.value;
|
||||
};
|
||||
const setIsManualClose = (value) => {
|
||||
isManualClose.value = value;
|
||||
};
|
||||
const getIsManualClose = () => {
|
||||
return isManualClose.value;
|
||||
};
|
||||
|
||||
const iceserver = {
|
||||
iceServers: [
|
||||
{
|
||||
// urls: "stun:stun.l.google.com:19302"
|
||||
urls: "stun:8.134.92.199:3478",
|
||||
},
|
||||
{
|
||||
urls: "turn:8.134.92.199:3478",
|
||||
username: "test",
|
||||
credential: "123456",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// 连接WebSocket
|
||||
export const connectVoicesocket = () => {
|
||||
const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
|
||||
const host = window.location.host;
|
||||
const socketUrl = `${protocol}${host}/voice?u_id=${userinfo.user.u_id}&u_name=${userinfo.user.u_name}`;
|
||||
|
||||
if (socket.value && socket.value.readyState !== WebSocket.CLOSED) {
|
||||
console.log("还在重连中...");
|
||||
return;
|
||||
}
|
||||
const retrytime = getRetryCount();
|
||||
if (retrytime >= 10) {
|
||||
console.log("重连失败,请稍后再试");
|
||||
return;
|
||||
}
|
||||
console.log(retrytime);
|
||||
socket.value = new WebSocket(socketUrl);
|
||||
|
||||
socket.value.onopen = (event) => {
|
||||
console.log("Voice连接已建立", event);
|
||||
setReconnectScheduled(false);
|
||||
setIsManualClose(false);
|
||||
resetRetryCount();
|
||||
};
|
||||
|
||||
// 处理消息逻辑
|
||||
socket.value.onmessage = async (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === "status") {
|
||||
ElMessage.error("对方已离线");
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
} else if (data.type === "incomingcall") {
|
||||
// 通话请求处理
|
||||
oncall.setTarget(data.from, data.from_name, data.from_avatar);
|
||||
oncall.panelOn();
|
||||
oncall.callingOn();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
} else if (data.type === "pickup") {
|
||||
ElMessage.success("对方已接听,等待连接中...");
|
||||
try {
|
||||
await initRTCconnection();
|
||||
RTCpeerConnection.value.onicecandidate = (event) => {
|
||||
if (event.candidate) {
|
||||
console.log("发送candidate", event.candidate);
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "candidate",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
candidate: event.candidate,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
}
|
||||
};
|
||||
|
||||
RTCpeerConnection.value.ontrack = (event) => {
|
||||
console.log("收到对方音频流", event);
|
||||
oncall.setRemoteStream(event.streams[0]);
|
||||
};
|
||||
} catch (e) {
|
||||
console.log("webRTC初始化失败", e);
|
||||
}
|
||||
|
||||
const offer = await RTCpeerConnection.value.createOffer({
|
||||
offerToReceiveAudio: 1,
|
||||
});
|
||||
|
||||
await RTCpeerConnection.value.setLocalDescription(offer);
|
||||
|
||||
// 发送offer
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "offer",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
offer: offer,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
} else if (data.type === "hangup") {
|
||||
ElMessage.success("对方已挂断");
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
oncall.resetStream();
|
||||
} else if (data.content === "offer") {
|
||||
ElMessage.success("收到对方offer");
|
||||
console.log("收到对方offer", data);
|
||||
|
||||
try {
|
||||
await initRTCconnection();
|
||||
|
||||
RTCpeerConnection.value.onicecandidate = (event) => {
|
||||
if (event.candidate) {
|
||||
console.log("发送candidate", event.candidate);
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "candidate",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
candidate: event.candidate,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
}
|
||||
};
|
||||
|
||||
RTCpeerConnection.value.ontrack = (event) => {
|
||||
console.log("收到对方音频流", event);
|
||||
oncall.setRemoteStream(event.streams[0]);
|
||||
};
|
||||
} catch (e) {
|
||||
console.log("webRTC初始化失败", e);
|
||||
}
|
||||
|
||||
await RTCpeerConnection.value.setRemoteDescription(data.offer);
|
||||
const answer = await RTCpeerConnection.value.createAnswer();
|
||||
await RTCpeerConnection.value.setLocalDescription(answer);
|
||||
|
||||
// 发送answer
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "answer",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
answer: answer,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
} else if (data.content === "answer") {
|
||||
ElMessage.success("对方已接受");
|
||||
console.log("对方已接受", data);
|
||||
await RTCpeerConnection.value.setRemoteDescription(data.answer);
|
||||
} else if (data.content === "candidate") {
|
||||
console.log("收到candidate", data);
|
||||
await RTCpeerConnection.value.addIceCandidate(data.candidate);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("VoiceSocket消息格式错误", e);
|
||||
}
|
||||
};
|
||||
|
||||
socket.value.onerror = (error) => {
|
||||
console.error("Voicesocket发生错误:", error);
|
||||
setReconnectScheduled(true);
|
||||
socket.value.close();
|
||||
};
|
||||
|
||||
socket.value.onclose = (event) => {
|
||||
if (!getIsManualClose()) {
|
||||
if (getReconnectScheduled()) {
|
||||
socket.value = null;
|
||||
addRetryCount();
|
||||
setTimeout(reConnectVoicesocket, 5000);
|
||||
setReconnectScheduled(false);
|
||||
} else {
|
||||
console.log("Voicesocket因为浏览器省电设置断开");
|
||||
console.log("Voicesocket连接已关闭", event);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// 断开Voicesocket连接
|
||||
export const disconnectVoicesocket = () => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.close();
|
||||
}
|
||||
};
|
||||
|
||||
// 重连机制
|
||||
export const reConnectVoicesocket = () => {
|
||||
connectVoicesocket();
|
||||
};
|
||||
|
||||
// 发送消息
|
||||
export const sendMessage = (message) => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.send(message);
|
||||
} else {
|
||||
console.warn("Voicesocket未连接,无法发送消息");
|
||||
}
|
||||
};
|
||||
|
||||
//没有错误的重连,只是浏览器在后台断开了连接
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
} else {
|
||||
if (!getIsManualClose() && socket.value.readyState === WebSocket.CLOSED) {
|
||||
if (getReconnectScheduled()) {
|
||||
return;
|
||||
}
|
||||
reConnectVoicesocket();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//WebRTC连接相关代码
|
||||
const RTCpeerConnection = ref(null);
|
||||
|
||||
export const getlocalStream = async () => {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
console.log("获取本地音频流成功", stream);
|
||||
return stream;
|
||||
// // 获取音频和视频轨道
|
||||
// const audioTrack = stream.getAudioTracks()[0];
|
||||
// // 将轨道添加到 RTCPeerConnection
|
||||
// peerConnection.addTrack(audioTrack, stream);
|
||||
};
|
||||
|
||||
const initRTCconnection = async () => {
|
||||
RTCpeerConnection.value = new RTCPeerConnection(iceserver);
|
||||
const stream = await getlocalStream();
|
||||
RTCpeerConnection.value.addTrack(stream.getAudioTracks()[0], stream);
|
||||
};
|
||||
|
||||
export const hangup = () => {
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
oncall.resetStream();
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
|
||||
const message = {
|
||||
type: "hangup",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
};
|
||||
import { ref } from "vue";
|
||||
import { userInfoStore } from "@/store/user";
|
||||
import { onCallStore } from "@/store/VoiceTarget";
|
||||
import { ElMessage } from "element-plus";
|
||||
|
||||
// userinfo 实例
|
||||
const userinfo = userInfoStore();
|
||||
// oncall 实例
|
||||
const oncall = onCallStore();
|
||||
// WebSocket 实例
|
||||
const socket = ref(null);
|
||||
|
||||
const isManualClose = ref(false);
|
||||
const reconnectScheduled = ref(false);
|
||||
const retryCount = ref(0);
|
||||
|
||||
const getRetryCount = () => {
|
||||
return retryCount.value;
|
||||
};
|
||||
const addRetryCount = () => {
|
||||
retryCount.value = retryCount.value + 1;
|
||||
};
|
||||
const resetRetryCount = () => {
|
||||
retryCount.value = 0;
|
||||
};
|
||||
const setReconnectScheduled = (value) => {
|
||||
reconnectScheduled.value = value;
|
||||
};
|
||||
const getReconnectScheduled = () => {
|
||||
return reconnectScheduled.value;
|
||||
};
|
||||
const setIsManualClose = (value) => {
|
||||
isManualClose.value = value;
|
||||
};
|
||||
const getIsManualClose = () => {
|
||||
return isManualClose.value;
|
||||
};
|
||||
|
||||
const iceserver = {
|
||||
iceServers: [
|
||||
{
|
||||
urls: process.env.STUN_URL,
|
||||
},
|
||||
{
|
||||
urls: process.env.TURN_URL,
|
||||
username: process.env.TURN_USERNAME,
|
||||
credential: process.env.TURN_CREDENTIAL,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// 连接WebSocket
|
||||
export const connectVoicesocket = () => {
|
||||
const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
|
||||
const host = window.location.host;
|
||||
const socketUrl = `${protocol}${host}/voice?u_id=${userinfo.user.u_id}&u_name=${userinfo.user.u_name}`;
|
||||
|
||||
if (socket.value && socket.value.readyState !== WebSocket.CLOSED) {
|
||||
console.log("还在重连中...");
|
||||
return;
|
||||
}
|
||||
const retrytime = getRetryCount();
|
||||
if (retrytime >= 10) {
|
||||
console.log("重连失败,请稍后再试");
|
||||
return;
|
||||
}
|
||||
console.log(retrytime);
|
||||
socket.value = new WebSocket(socketUrl);
|
||||
|
||||
socket.value.onopen = (event) => {
|
||||
console.log("Voice连接已建立", event);
|
||||
setReconnectScheduled(false);
|
||||
setIsManualClose(false);
|
||||
resetRetryCount();
|
||||
};
|
||||
|
||||
// 处理消息逻辑
|
||||
socket.value.onmessage = async (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === "status") {
|
||||
ElMessage.error("对方已离线");
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
} else if (data.type === "incomingcall") {
|
||||
// 通话请求处理
|
||||
oncall.setTarget(data.from, data.from_name, data.from_avatar);
|
||||
oncall.panelOn();
|
||||
oncall.callingOn();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
} else if (data.type === "pickup") {
|
||||
ElMessage.success("对方已接听,等待连接中...");
|
||||
try {
|
||||
await initRTCconnection();
|
||||
RTCpeerConnection.value.onicecandidate = (event) => {
|
||||
if (event.candidate) {
|
||||
console.log("发送candidate", event.candidate);
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "candidate",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
candidate: event.candidate,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
}
|
||||
};
|
||||
|
||||
RTCpeerConnection.value.ontrack = (event) => {
|
||||
console.log("收到对方音频流", event);
|
||||
oncall.setRemoteStream(event.streams[0]);
|
||||
};
|
||||
} catch (e) {
|
||||
console.log("webRTC初始化失败", e);
|
||||
}
|
||||
|
||||
const offer = await RTCpeerConnection.value.createOffer({
|
||||
offerToReceiveAudio: 1,
|
||||
});
|
||||
|
||||
await RTCpeerConnection.value.setLocalDescription(offer);
|
||||
|
||||
// 发送offer
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "offer",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
offer: offer,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
} else if (data.type === "hangup") {
|
||||
ElMessage.success("对方已挂断");
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
oncall.resetStream();
|
||||
} else if (data.content === "offer") {
|
||||
ElMessage.success("收到对方offer");
|
||||
console.log("收到对方offer", data);
|
||||
|
||||
try {
|
||||
await initRTCconnection();
|
||||
|
||||
RTCpeerConnection.value.onicecandidate = (event) => {
|
||||
if (event.candidate) {
|
||||
console.log("发送candidate", event.candidate);
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "candidate",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
candidate: event.candidate,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
}
|
||||
};
|
||||
|
||||
RTCpeerConnection.value.ontrack = (event) => {
|
||||
console.log("收到对方音频流", event);
|
||||
oncall.setRemoteStream(event.streams[0]);
|
||||
};
|
||||
} catch (e) {
|
||||
console.log("webRTC初始化失败", e);
|
||||
}
|
||||
|
||||
await RTCpeerConnection.value.setRemoteDescription(data.offer);
|
||||
const answer = await RTCpeerConnection.value.createAnswer();
|
||||
await RTCpeerConnection.value.setLocalDescription(answer);
|
||||
|
||||
// 发送answer
|
||||
const message = {
|
||||
type: "single",
|
||||
content: "answer",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
answer: answer,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
} else if (data.content === "answer") {
|
||||
ElMessage.success("对方已接受");
|
||||
console.log("对方已接受", data);
|
||||
await RTCpeerConnection.value.setRemoteDescription(data.answer);
|
||||
} else if (data.content === "candidate") {
|
||||
console.log("收到candidate", data);
|
||||
await RTCpeerConnection.value.addIceCandidate(data.candidate);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("VoiceSocket消息格式错误", e);
|
||||
}
|
||||
};
|
||||
|
||||
socket.value.onerror = (error) => {
|
||||
console.error("Voicesocket发生错误:", error);
|
||||
setReconnectScheduled(true);
|
||||
socket.value.close();
|
||||
};
|
||||
|
||||
socket.value.onclose = (event) => {
|
||||
if (!getIsManualClose()) {
|
||||
if (getReconnectScheduled()) {
|
||||
socket.value = null;
|
||||
addRetryCount();
|
||||
setTimeout(reConnectVoicesocket, 5000);
|
||||
setReconnectScheduled(false);
|
||||
} else {
|
||||
console.log("Voicesocket因为浏览器省电设置断开");
|
||||
console.log("Voicesocket连接已关闭", event);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// 断开Voicesocket连接
|
||||
export const disconnectVoicesocket = () => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.close();
|
||||
}
|
||||
};
|
||||
|
||||
// 重连机制
|
||||
export const reConnectVoicesocket = () => {
|
||||
connectVoicesocket();
|
||||
};
|
||||
|
||||
// 发送消息
|
||||
export const sendMessage = (message) => {
|
||||
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
|
||||
socket.value.send(message);
|
||||
} else {
|
||||
console.warn("Voicesocket未连接,无法发送消息");
|
||||
}
|
||||
};
|
||||
|
||||
//没有错误的重连,只是浏览器在后台断开了连接
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
} else {
|
||||
if (!getIsManualClose() && socket.value.readyState === WebSocket.CLOSED) {
|
||||
if (getReconnectScheduled()) {
|
||||
return;
|
||||
}
|
||||
reConnectVoicesocket();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//WebRTC连接相关代码
|
||||
export const RTCpeerConnection = ref(null);
|
||||
|
||||
const getlocalStream = async () => {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
console.log("获取本地音频流成功", stream);
|
||||
return stream;
|
||||
// // 获取音频和视频轨道
|
||||
// const audioTrack = stream.getAudioTracks()[0];
|
||||
// // 将轨道添加到 RTCPeerConnection
|
||||
// peerConnection.addTrack(audioTrack, stream);
|
||||
};
|
||||
|
||||
const initRTCconnection = async () => {
|
||||
RTCpeerConnection.value = new RTCPeerConnection(iceserver);
|
||||
const stream = await getlocalStream();
|
||||
RTCpeerConnection.value.addTrack(stream.getAudioTracks()[0], stream);
|
||||
};
|
||||
|
||||
export const hangup = () => {
|
||||
oncall.panelOff();
|
||||
oncall.callingOff();
|
||||
oncall.fromOff();
|
||||
oncall.statusOff();
|
||||
oncall.resetStream();
|
||||
RTCpeerConnection.value.close();
|
||||
RTCpeerConnection.value = null;
|
||||
|
||||
const message = {
|
||||
type: "hangup",
|
||||
from: userinfo.user.u_id,
|
||||
to: oncall.target.u_id,
|
||||
};
|
||||
sendMessage(JSON.stringify(message));
|
||||
};
|
||||
131
vite.config.js
131
vite.config.js
@@ -1,61 +1,70 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
}
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8080', // 后端服务器地址
|
||||
changeOrigin: true, // 允许跨域
|
||||
rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径,去掉 /api 前缀
|
||||
},
|
||||
'/proxy': {
|
||||
target: 'http://localhost:3000', // 代理服务器的地址
|
||||
changeOrigin: true, // 必须设置为 true,才能避免跨域问题
|
||||
// rewrite: (path) => path.replace(/^\/proxy/, ''), // 重写路径,去掉 /api 前缀
|
||||
|
||||
},
|
||||
'/ws': {
|
||||
target: 'ws://localhost:8080',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// '/ws': {
|
||||
// target: 'ws://localhost:8080',
|
||||
// changeOrigin: true,
|
||||
// ws: true,
|
||||
// }
|
||||
},
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
},
|
||||
// server: {
|
||||
// https:{
|
||||
// key: fs.readFileSync('./cert/merlin.xin.key'),
|
||||
// cert: fs.readFileSync('./cert/merlin.xin.pem'),
|
||||
// },
|
||||
// proxy: {
|
||||
// '/api': {
|
||||
// target: 'https://localhost:8443', // 后端服务器地址
|
||||
// changeOrigin: true, // 允许跨域
|
||||
// rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径,去掉 /api 前缀
|
||||
// },
|
||||
// '/online':{
|
||||
// target:'wss://localhost:8443/online',
|
||||
// changeOrigin:true,
|
||||
// ws:true,
|
||||
// },
|
||||
// '/voice':{
|
||||
// target:'wss://localhost:8443/voice',
|
||||
// changeOrigin:true,
|
||||
// ws:true,
|
||||
// }
|
||||
// },
|
||||
// },
|
||||
});
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
}
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8080', // 后端服务器地址
|
||||
changeOrigin: true, // 允许跨域
|
||||
rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径,去掉 /api 前缀
|
||||
},
|
||||
'/proxy': {
|
||||
target: 'http://localhost:3000', // 代理服务器的地址
|
||||
changeOrigin: true, // 必须设置为 true,才能避免跨域问题
|
||||
// rewrite: (path) => path.replace(/^\/proxy/, ''), // 重写路径,去掉 /api 前缀
|
||||
|
||||
},
|
||||
'/ws': {
|
||||
target: 'ws://localhost:8080',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// '/ws': {
|
||||
// target: 'ws://localhost:8080',
|
||||
// changeOrigin: true,
|
||||
// ws: true,
|
||||
// }
|
||||
},
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
},
|
||||
// server: {
|
||||
// https:{
|
||||
// key: fs.readFileSync('./cert/merlin.xin.key'),
|
||||
// cert: fs.readFileSync('./cert/merlin.xin.pem'),
|
||||
// },
|
||||
// proxy: {
|
||||
// '/api': {
|
||||
// target: 'https://localhost:8443', // 后端服务器地址
|
||||
// changeOrigin: true, // 允许跨域
|
||||
// rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径,去掉 /api 前缀
|
||||
// },
|
||||
// '/online':{
|
||||
// target:'wss://localhost:8443/online',
|
||||
// changeOrigin:true,
|
||||
// ws:true,
|
||||
// },
|
||||
// '/voice':{
|
||||
// target:'wss://localhost:8443/voice',
|
||||
// changeOrigin:true,
|
||||
// ws:true,
|
||||
// }
|
||||
// },
|
||||
// },
|
||||
define: {
|
||||
'process.env.STUN_URL': JSON.stringify(process.env.STUN_URL),
|
||||
'process.env.TURN_URL': JSON.stringify(process.env.TURN_URL),
|
||||
'process.env.TURN_USERNAME': JSON.stringify(process.env.TURN_USERNAME),
|
||||
'process.env.TURN_CREDENTIAL': JSON.stringify(process.env.TURN_CREDENTIAL),
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user