替换 vite 架构

This commit is contained in:
GeekMaster
2025-05-26 14:14:29 +08:00
parent 94a5187e75
commit b1ddcef593
20 changed files with 937 additions and 782 deletions

View File

@@ -17,45 +17,45 @@
</div>
</template>
<script setup>
import { ref } from "vue";
import { showMessageError } from "@/utils/dialog";
import { getLicenseInfo, getSystemInfo } from "@/store/cache";
import { getLicenseInfo, getSystemInfo } from '@/store/cache'
import { showMessageError } from '@/utils/dialog'
import { ref } from 'vue'
const title = ref("");
const version = ref(process.env.VUE_APP_VERSION);
const gitURL = ref(process.env.VUE_APP_GITHUB_URL);
const copyRight = ref("");
const icp = ref("");
const license = ref({});
const title = ref('')
const version = ref(import.meta.env.VITE_VERSION)
const gitURL = ref(import.meta.env.VITE_GITHUB_URL)
const copyRight = ref('')
const icp = ref('')
const license = ref({})
const props = defineProps({
textColor: {
type: String,
default: "#ffffff"
}
});
default: '#ffffff',
},
})
// 获取系统配置
getSystemInfo()
.then((res) => {
title.value = res.data.title ?? process.env.VUE_APP_TITLE;
title.value = res.data.title ?? import.meta.env.VITE_TITLE
copyRight.value =
(res.data.copyright ? res.data.copyright : "极客学长") +
" © 2023 - " +
(res.data.copyright ? res.data.copyright : '极客学长') +
' © 2023 - ' +
new Date().getFullYear() +
" All rights reserved";
icp.value = res.data.icp;
' All rights reserved'
icp.value = res.data.icp
})
.catch((e) => {
showMessageError("获取系统配置失败:" + e.message);
});
showMessageError('获取系统配置失败:' + e.message)
})
getLicenseInfo()
.then((res) => {
license.value = res.data;
license.value = res.data
})
.catch((e) => {
showMessageError("获取 License 失败:" + e.message);
});
showMessageError('获取 License 失败:' + e.message)
})
</script>
<style scoped lang="stylus">

View File

@@ -13,7 +13,14 @@
</div>
<div class="block">
<el-input placeholder="请输入密码(8-16位)" maxlength="16" size="large" v-model="data.password" show-password autocomplete="off">
<el-input
placeholder="请输入密码(8-16位)"
maxlength="16"
size="large"
v-model="data.password"
show-password
autocomplete="off"
>
<template #prefix>
<el-icon>
<Lock />
@@ -24,7 +31,9 @@
<el-row class="btn-row" :gutter="20">
<el-col :span="24">
<el-button class="login-btn" type="primary" size="large" @click="submitLogin"> </el-button>
<el-button class="login-btn" type="primary" size="large" @click="submitLogin"
> </el-button
>
</el-col>
</el-row>
@@ -33,7 +42,9 @@
还没有账号
<el-button size="small" @click="login = false">注册</el-button>
<el-button type="info" class="forget" size="small" @click="showResetPass = true">忘记密码</el-button>
<el-button type="info" class="forget" size="small" @click="showResetPass = true"
>忘记密码</el-button
>
</div>
<div v-if="wechatLoginURL !== ''">
<el-divider>
@@ -42,7 +53,11 @@
<div class="c-login flex justify-center">
<div class="p-2 w-full">
<a :href="wechatLoginURL">
<el-button type="success" class="w-full" size="large" @click="setRoute(router.currentRoute.value.path)"
<el-button
type="success"
class="w-full"
size="large"
@click="setRoute(router.currentRoute.value.path)"
><i class="iconfont icon-wechat mr-2"></i> 微信登录
</el-button>
</a>
@@ -58,7 +73,13 @@
<el-tabs v-model="activeName" class="demo-tabs">
<el-tab-pane label="手机注册" name="mobile" v-if="enableMobile">
<div class="block">
<el-input placeholder="手机号码" size="large" v-model="data.mobile" maxlength="11" autocomplete="off">
<el-input
placeholder="手机号码"
size="large"
v-model="data.mobile"
maxlength="11"
autocomplete="off"
>
<template #prefix>
<el-icon>
<Iphone />
@@ -69,7 +90,13 @@
<div class="block">
<el-row :gutter="10">
<el-col :span="12">
<el-input placeholder="验证码" size="large" maxlength="30" v-model="data.code" autocomplete="off">
<el-input
placeholder="验证码"
size="large"
maxlength="30"
v-model="data.code"
autocomplete="off"
>
<template #prefix>
<el-icon>
<Checked />
@@ -96,7 +123,13 @@
<div class="block">
<el-row :gutter="10">
<el-col :span="12">
<el-input placeholder="验证码" size="large" maxlength="30" v-model="data.code" autocomplete="off">
<el-input
placeholder="验证码"
size="large"
maxlength="30"
v-model="data.code"
autocomplete="off"
>
<template #prefix>
<el-icon>
<Checked />
@@ -112,7 +145,12 @@
</el-tab-pane>
<el-tab-pane label="用户名注册" name="username" v-if="enableUser">
<div class="block">
<el-input placeholder="用户名" size="large" v-model="data.username" autocomplete="off">
<el-input
placeholder="用户名"
size="large"
v-model="data.username"
autocomplete="off"
>
<template #prefix>
<el-icon>
<Iphone />
@@ -124,7 +162,14 @@
</el-tabs>
<div class="block">
<el-input placeholder="请输入密码(8-16位)" maxlength="16" size="large" v-model="data.password" show-password autocomplete="off">
<el-input
placeholder="请输入密码(8-16位)"
maxlength="16"
size="large"
v-model="data.password"
show-password
autocomplete="off"
>
<template #prefix>
<el-icon>
<Lock />
@@ -134,7 +179,14 @@
</div>
<div class="block">
<el-input placeholder="重复密码(8-16位)" size="large" maxlength="16" v-model="data.repass" show-password autocomplete="off">
<el-input
placeholder="重复密码(8-16位)"
size="large"
maxlength="16"
v-model="data.repass"
show-password
autocomplete="off"
>
<template #prefix>
<el-icon>
<Lock />
@@ -144,7 +196,12 @@
</div>
<div class="block">
<el-input placeholder="邀请码(可选)" size="large" v-model="data.invite_code" autocomplete="off">
<el-input
placeholder="邀请码(可选)"
size="large"
v-model="data.invite_code"
autocomplete="off"
>
<template #prefix>
<el-icon>
<Message />
@@ -154,7 +211,9 @@
</div>
<div class="w-full">
<el-button class="login-btn w-full" type="primary" size="large" @click="submitRegister"> </el-button>
<el-button class="login-btn w-full" type="primary" size="large" @click="submitRegister"
> </el-button
>
</div>
<div class="text text-sm flex justify-center items-center w-full pt-3">
@@ -188,193 +247,193 @@
</template>
<script setup>
import { onMounted, ref, watch } from "vue";
import { httpGet, httpPost } from "@/utils/http";
import { ElMessage } from "element-plus";
import { setUserToken } from "@/store/session";
import { validateEmail, validateMobile } from "@/utils/validate";
import { Checked, Close, Iphone, Lock, Message } from "@element-plus/icons-vue";
import SendMsg from "@/components/SendMsg.vue";
import { arrayContains } from "@/utils/libs";
import { getSystemInfo } from "@/store/cache";
import Captcha from "@/components/Captcha.vue";
import ResetPass from "@/components/ResetPass.vue";
import { setRoute } from "@/store/system";
import { useRouter } from "vue-router";
import { useSharedStore } from "@/store/sharedata";
import Captcha from '@/components/Captcha.vue'
import ResetPass from '@/components/ResetPass.vue'
import SendMsg from '@/components/SendMsg.vue'
import { getSystemInfo } from '@/store/cache'
import { setUserToken } from '@/store/session'
import { useSharedStore } from '@/store/sharedata'
import { setRoute } from '@/store/system'
import { httpGet, httpPost } from '@/utils/http'
import { arrayContains } from '@/utils/libs'
import { validateEmail, validateMobile } from '@/utils/validate'
import { Checked, Iphone, Lock, Message } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
// eslint-disable-next-line no-undef
const props = defineProps({
show: Boolean,
});
const showDialog = ref(false);
})
const showDialog = ref(false)
watch(
() => props.show,
(newValue) => {
showDialog.value = newValue;
showDialog.value = newValue
}
);
)
const login = ref(true);
const login = ref(true)
const data = ref({
username: process.env.VUE_APP_USER,
password: process.env.VUE_APP_PASS,
mobile: "",
email: "",
repass: "",
code: "",
invite_code: "",
});
const enableMobile = ref(false);
const enableEmail = ref(false);
const enableUser = ref(false);
const enableRegister = ref(true);
const wechatLoginURL = ref("");
const activeName = ref("");
const wxImg = ref("/images/wx.png");
const captchaRef = ref(null);
username: import.meta.env.VITE_USER,
password: import.meta.env.VITE_PASS,
mobile: '',
email: '',
repass: '',
code: '',
invite_code: '',
})
const enableMobile = ref(false)
const enableEmail = ref(false)
const enableUser = ref(false)
const enableRegister = ref(true)
const wechatLoginURL = ref('')
const activeName = ref('')
const wxImg = ref('/images/wx.png')
const captchaRef = ref(null)
// eslint-disable-next-line no-undef
const emits = defineEmits(["hide", "success"]);
const action = ref("login");
const enableVerify = ref(false);
const showResetPass = ref(false);
const router = useRouter();
const store = useSharedStore();
const emits = defineEmits(['hide', 'success'])
const action = ref('login')
const enableVerify = ref(false)
const showResetPass = ref(false)
const router = useRouter()
const store = useSharedStore()
onMounted(() => {
const returnURL = `${location.protocol}//${location.host}/login/callback?action=login`;
httpGet("/api/user/clogin?return_url=" + returnURL)
const returnURL = `${location.protocol}//${location.host}/login/callback?action=login`
httpGet('/api/user/clogin?return_url=' + returnURL)
.then((res) => {
wechatLoginURL.value = res.data.url;
wechatLoginURL.value = res.data.url
})
.catch((e) => {
console.log(e.message);
});
console.log(e.message)
})
getSystemInfo()
.then((res) => {
if (res.data) {
const registerWays = res.data["register_ways"];
if (arrayContains(registerWays, "username")) {
enableUser.value = true;
activeName.value = "username";
const registerWays = res.data['register_ways']
if (arrayContains(registerWays, 'username')) {
enableUser.value = true
activeName.value = 'username'
}
if (arrayContains(registerWays, "email")) {
enableEmail.value = true;
activeName.value = "email";
if (arrayContains(registerWays, 'email')) {
enableEmail.value = true
activeName.value = 'email'
}
if (arrayContains(registerWays, "mobile")) {
enableMobile.value = true;
activeName.value = "mobile";
if (arrayContains(registerWays, 'mobile')) {
enableMobile.value = true
activeName.value = 'mobile'
}
// 是否启用注册
enableRegister.value = res.data["enabled_register"];
enableRegister.value = res.data['enabled_register']
// 使用后台上传的客服微信二维码
if (res.data["wechat_card_url"] !== "") {
wxImg.value = res.data["wechat_card_url"];
if (res.data['wechat_card_url'] !== '') {
wxImg.value = res.data['wechat_card_url']
}
enableVerify.value = res.data["enabled_verify"];
enableVerify.value = res.data['enabled_verify']
}
})
.catch((e) => {
ElMessage.error("获取系统配置失败:" + e.message);
});
});
ElMessage.error('获取系统配置失败:' + e.message)
})
})
const submit = (verifyData) => {
if (action.value === "login") {
doLogin(verifyData);
} else if (action.value === "register") {
doRegister(verifyData);
if (action.value === 'login') {
doLogin(verifyData)
} else if (action.value === 'register') {
doRegister(verifyData)
}
};
}
// 登录操作
const submitLogin = () => {
if (!data.value.username) {
return ElMessage.error("请输入用户名");
return ElMessage.error('请输入用户名')
}
if (!data.value.password) {
return ElMessage.error("请输入密码");
return ElMessage.error('请输入密码')
}
if (enableVerify.value) {
captchaRef.value.loadCaptcha();
action.value = "login";
captchaRef.value.loadCaptcha()
action.value = 'login'
} else {
doLogin({});
doLogin({})
}
};
}
const doLogin = (verifyData) => {
data.value.key = verifyData.key;
data.value.dots = verifyData.dots;
data.value.x = verifyData.x;
httpPost("/api/user/login", data.value)
data.value.key = verifyData.key
data.value.dots = verifyData.dots
data.value.x = verifyData.x
httpPost('/api/user/login', data.value)
.then((res) => {
setUserToken(res.data.token);
store.setIsLogin(true);
ElMessage.success("登录成功!");
emits("hide");
emits("success");
setUserToken(res.data.token)
store.setIsLogin(true)
ElMessage.success('登录成功!')
emits('hide')
emits('success')
})
.catch((e) => {
ElMessage.error("登录失败," + e.message);
});
};
ElMessage.error('登录失败,' + e.message)
})
}
// 注册操作
const submitRegister = () => {
if (activeName.value === "username" && data.value.username === "") {
return ElMessage.error("请输入用户名");
if (activeName.value === 'username' && data.value.username === '') {
return ElMessage.error('请输入用户名')
}
if (activeName.value === "mobile" && !validateMobile(data.value.mobile)) {
return ElMessage.error("请输入合法的手机号");
if (activeName.value === 'mobile' && !validateMobile(data.value.mobile)) {
return ElMessage.error('请输入合法的手机号')
}
if (activeName.value === "email" && !validateEmail(data.value.email)) {
return ElMessage.error("请输入合法的邮箱地址");
if (activeName.value === 'email' && !validateEmail(data.value.email)) {
return ElMessage.error('请输入合法的邮箱地址')
}
if (data.value.password.length < 8) {
return ElMessage.error("密码的长度为8-16个字符");
return ElMessage.error('密码的长度为8-16个字符')
}
if (data.value.repass !== data.value.password) {
return ElMessage.error("两次输入密码不一致");
return ElMessage.error('两次输入密码不一致')
}
if ((activeName.value === "mobile" || activeName.value === "email") && data.value.code === "") {
return ElMessage.error("请输入验证码");
if ((activeName.value === 'mobile' || activeName.value === 'email') && data.value.code === '') {
return ElMessage.error('请输入验证码')
}
if (enableVerify.value && activeName.value === "username") {
captchaRef.value.loadCaptcha();
action.value = "register";
if (enableVerify.value && activeName.value === 'username') {
captchaRef.value.loadCaptcha()
action.value = 'register'
} else {
doRegister({});
doRegister({})
}
};
}
const doRegister = (verifyData) => {
data.value.key = verifyData.key;
data.value.dots = verifyData.dots;
data.value.x = verifyData.x;
data.value.reg_way = activeName.value;
httpPost("/api/user/register", data.value)
data.value.key = verifyData.key
data.value.dots = verifyData.dots
data.value.x = verifyData.x
data.value.reg_way = activeName.value
httpPost('/api/user/register', data.value)
.then((res) => {
setUserToken(res.data.token);
setUserToken(res.data.token)
ElMessage.success({
message: "注册成功!",
message: '注册成功!',
onClose: () => {
emits("hide");
emits("success");
emits('hide')
emits('success')
},
duration: 1000,
});
})
})
.catch((e) => {
ElMessage.error("注册失败," + e.message);
});
};
ElMessage.error('注册失败,' + e.message)
})
}
</script>
<style lang="stylus">

View File

@@ -38,11 +38,7 @@
<div class="call-controls">
<el-tooltip content="长按发送语音" placement="top">
<ripple-button>
<button
class="call-button answer"
@mousedown="startRecording"
@mouseup="stopRecording"
>
<button class="call-button answer" @mousedown="startRecording" @mouseup="stopRecording">
<i class="iconfont icon-mic-bold"></i>
</button>
</ripple-button>
@@ -58,159 +54,155 @@
</template>
<script setup>
import RippleButton from "@/components/ui/RippleButton.vue";
import { ref, onMounted, onUnmounted } from "vue";
import { RealtimeClient } from "@openai/realtime-api-beta";
import { WavRecorder, WavStreamPlayer } from "@/lib/wavtools/index.js";
import { instructions } from "@/utils/conversation_config.js";
import { WavRenderer } from "@/utils/wav_renderer";
import { showMessageError } from "@/utils/dialog";
import { getUserToken } from "@/store/session";
import RippleButton from '@/components/ui/RippleButton.vue'
import { WavRecorder, WavStreamPlayer } from '@/lib/wavtools/index.js'
import { getUserToken } from '@/store/session'
import { instructions } from '@/utils/conversation_config.js'
import { showMessageError } from '@/utils/dialog'
import { WavRenderer } from '@/utils/wav_renderer'
import { RealtimeClient } from '@openai/realtime-api-beta'
import { onMounted, onUnmounted, ref } from 'vue'
// eslint-disable-next-line no-unused-vars,no-undef
const props = defineProps({
height: {
type: String,
default: "100vh"
}
});
default: '100vh',
},
})
// eslint-disable-next-line no-undef
const emits = defineEmits(["close"]);
const emits = defineEmits(['close'])
/********************** connection animation code *************************/
const fullText = "正在接通中...";
const connectingText = ref("");
let index = 0;
const fullText = '正在接通中...'
const connectingText = ref('')
let index = 0
const typeText = () => {
if (index < fullText.length) {
connectingText.value += fullText[index];
index++;
setTimeout(typeText, 200); // 每300毫秒显示一个字
connectingText.value += fullText[index]
index++
setTimeout(typeText, 200) // 每300毫秒显示一个字
} else {
setTimeout(() => {
connectingText.value = "";
index = 0;
typeText();
}, 1000); // 等待1秒后重新开始
connectingText.value = ''
index = 0
typeText()
}, 1000) // 等待1秒后重新开始
}
};
}
/*************************** end of code ****************************************/
/********************** conversation process code ***************************/
const leftVoiceActive = ref(false);
const rightVoiceActive = ref(false);
const leftVoiceActive = ref(false)
const rightVoiceActive = ref(false)
const animateVoice = () => {
leftVoiceActive.value = Math.random() > 0.5;
rightVoiceActive.value = Math.random() > 0.5;
};
leftVoiceActive.value = Math.random() > 0.5
rightVoiceActive.value = Math.random() > 0.5
}
const wavRecorder = ref(new WavRecorder({ sampleRate: 24000 }));
const wavStreamPlayer = ref(new WavStreamPlayer({ sampleRate: 24000 }));
let host = process.env.VUE_APP_WS_HOST;
if (host === "") {
if (location.protocol === "https:") {
host = "wss://" + location.host;
const wavRecorder = ref(new WavRecorder({ sampleRate: 24000 }))
const wavStreamPlayer = ref(new WavStreamPlayer({ sampleRate: 24000 }))
let host = import.meta.env.VITE_WS_HOST
if (host === '') {
if (location.protocol === 'https:') {
host = 'wss://' + location.host
} else {
host = "ws://" + location.host;
host = 'ws://' + location.host
}
}
const client = ref(
new RealtimeClient({
url: `${host}/api/realtime`,
apiKey: getUserToken(),
dangerouslyAllowAPIKeyInBrowser: true
dangerouslyAllowAPIKeyInBrowser: true,
})
);
)
// // Set up client instructions and transcription
client.value.updateSession({
instructions: instructions,
turn_detection: null,
input_audio_transcription: { model: "whisper-1" },
voice: "alloy"
});
input_audio_transcription: { model: 'whisper-1' },
voice: 'alloy',
})
// set voice wave canvas
const clientCanvasRef = ref(null);
const serverCanvasRef = ref(null);
const isConnected = ref(false);
const isRecording = ref(false);
const backgroundAudio = ref(null);
const hangUpAudio = ref(null);
const clientCanvasRef = ref(null)
const serverCanvasRef = ref(null)
const isConnected = ref(false)
const isRecording = ref(false)
const backgroundAudio = ref(null)
const hangUpAudio = ref(null)
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
return new Promise((resolve) => setTimeout(resolve, ms))
}
const connect = async () => {
if (isConnected.value) {
return;
return
}
// 播放背景音乐
if (backgroundAudio.value) {
backgroundAudio.value.play().catch((error) => {
console.error("播放失败,可能是浏览器的自动播放策略导致的:", error);
});
console.error('播放失败,可能是浏览器的自动播放策略导致的:', error)
})
}
// 模拟拨号延时
await sleep(3000);
await sleep(3000)
try {
await client.value.connect();
await wavRecorder.value.begin();
await wavStreamPlayer.value.connect();
console.log("对话连接成功!");
await client.value.connect()
await wavRecorder.value.begin()
await wavStreamPlayer.value.connect()
console.log('对话连接成功!')
if (!client.value.isConnected()) {
return;
return
}
isConnected.value = true;
backgroundAudio.value?.pause();
backgroundAudio.value.currentTime = 0;
isConnected.value = true
backgroundAudio.value?.pause()
backgroundAudio.value.currentTime = 0
client.value.sendUserMessageContent([
{
type: "input_text",
text: "你好,我是极客学长!"
}
]);
if (client.value.getTurnDetectionType() === "server_vad") {
await wavRecorder.value.record((data) =>
client.value.appendInputAudio(data.mono)
);
type: 'input_text',
text: '你好,我是极客学长!',
},
])
if (client.value.getTurnDetectionType() === 'server_vad') {
await wavRecorder.value.record((data) => client.value.appendInputAudio(data.mono))
}
} catch (e) {
console.error(e);
console.error(e)
}
};
}
// 开始语音输入
const startRecording = async () => {
if (isRecording.value) {
return;
return
}
isRecording.value = true;
isRecording.value = true
try {
const trackSampleOffset = await wavStreamPlayer.value.interrupt();
const trackSampleOffset = await wavStreamPlayer.value.interrupt()
if (trackSampleOffset?.trackId) {
const { trackId, offset } = trackSampleOffset;
client.value.cancelResponse(trackId, offset);
const { trackId, offset } = trackSampleOffset
client.value.cancelResponse(trackId, offset)
}
await wavRecorder.value.record((data) =>
client.value.appendInputAudio(data.mono)
);
await wavRecorder.value.record((data) => client.value.appendInputAudio(data.mono))
} catch (e) {
console.error(e);
console.error(e)
}
};
}
// 结束语音输入
const stopRecording = async () => {
try {
isRecording.value = false;
await wavRecorder.value.pause();
client.value.createResponse();
isRecording.value = false
await wavRecorder.value.pause()
client.value.createResponse()
} catch (e) {
console.error(e);
console.error(e)
}
};
}
// const changeTurnEndType = async (value) => {
// if (value === 'none' && wavRecorder.value.getStatus() === 'recording') {
@@ -228,108 +220,108 @@ const stopRecording = async () => {
// 初始化 WaveRecorder 组件和 RealtimeClient 事件处理
const initialize = async () => {
// Set up render loops for the visualization canvas
let isLoaded = true;
let isLoaded = true
const render = () => {
if (isLoaded) {
if (clientCanvasRef.value) {
const canvas = clientCanvasRef.value;
const canvas = clientCanvasRef.value
if (!canvas.width || !canvas.height) {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
canvas.width = canvas.offsetWidth
canvas.height = canvas.offsetHeight
}
const ctx = canvas.getContext("2d");
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height)
const result = wavRecorder.value.recording
? wavRecorder.value.getFrequencies("voice")
: { values: new Float32Array([0]) };
WavRenderer.drawBars(canvas, ctx, result.values, "#0099ff", 10, 0, 8);
? wavRecorder.value.getFrequencies('voice')
: { values: new Float32Array([0]) }
WavRenderer.drawBars(canvas, ctx, result.values, '#0099ff', 10, 0, 8)
}
}
if (serverCanvasRef.value) {
const canvas = serverCanvasRef.value;
const canvas = serverCanvasRef.value
if (!canvas.width || !canvas.height) {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
canvas.width = canvas.offsetWidth
canvas.height = canvas.offsetHeight
}
const ctx = canvas.getContext("2d");
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height)
const result = wavStreamPlayer.value.analyser
? wavStreamPlayer.value.getFrequencies("voice")
: { values: new Float32Array([0]) };
WavRenderer.drawBars(canvas, ctx, result.values, "#009900", 10, 0, 8);
? wavStreamPlayer.value.getFrequencies('voice')
: { values: new Float32Array([0]) }
WavRenderer.drawBars(canvas, ctx, result.values, '#009900', 10, 0, 8)
}
}
requestAnimationFrame(render);
requestAnimationFrame(render)
}
};
render();
}
render()
client.value.on("error", (event) => {
showMessageError(event.error);
});
client.value.on('error', (event) => {
showMessageError(event.error)
})
client.value.on("realtime.event", (re) => {
if (re.event.type === "error") {
showMessageError(re.event.error);
client.value.on('realtime.event', (re) => {
if (re.event.type === 'error') {
showMessageError(re.event.error)
}
});
})
client.value.on("conversation.interrupted", async () => {
const trackSampleOffset = await wavStreamPlayer.value.interrupt();
client.value.on('conversation.interrupted', async () => {
const trackSampleOffset = await wavStreamPlayer.value.interrupt()
if (trackSampleOffset?.trackId) {
const { trackId, offset } = trackSampleOffset;
client.value.cancelResponse(trackId, offset);
const { trackId, offset } = trackSampleOffset
client.value.cancelResponse(trackId, offset)
}
});
})
client.value.on("conversation.updated", async ({ item, delta }) => {
client.value.on('conversation.updated', async ({ item, delta }) => {
// console.log('item updated', item, delta)
if (delta?.audio) {
wavStreamPlayer.value.add16BitPCM(delta.audio, item.id);
wavStreamPlayer.value.add16BitPCM(delta.audio, item.id)
}
});
};
})
}
const voiceInterval = ref(null);
const voiceInterval = ref(null)
onMounted(() => {
initialize();
initialize()
// 启动聊天进行中的动画
voiceInterval.value = setInterval(animateVoice, 200);
typeText();
});
voiceInterval.value = setInterval(animateVoice, 200)
typeText()
})
onUnmounted(() => {
clearInterval(voiceInterval.value);
client.value.reset();
});
clearInterval(voiceInterval.value)
client.value.reset()
})
// 挂断通话
const hangUp = async () => {
try {
isConnected.value = false;
isConnected.value = false
// 停止播放拨号音乐
if (backgroundAudio.value?.currentTime) {
backgroundAudio.value?.pause();
backgroundAudio.value.currentTime = 0;
backgroundAudio.value?.pause()
backgroundAudio.value.currentTime = 0
}
// 断开客户端的连接
client.value.reset();
client.value.reset()
// 中断语音输入和输出服务
await wavRecorder.value.end();
await wavStreamPlayer.value.interrupt();
await wavRecorder.value.end()
await wavStreamPlayer.value.interrupt()
} catch (e) {
console.error(e);
console.error(e)
} finally {
// 播放挂断音乐
hangUpAudio.value?.play();
emits("close");
hangUpAudio.value?.play()
emits('close')
}
};
}
// eslint-disable-next-line no-undef
defineExpose({ connect, hangUp });
defineExpose({ connect, hangUp })
</script>
<style scoped lang="stylus">

View File

@@ -58,63 +58,63 @@
</div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {getSystemInfo} from "@/store/cache";
import { getSystemInfo } from '@/store/cache'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
const title = ref(process.env.VUE_APP_TITLE);
const version = ref(process.env.VUE_APP_VERSION);
const title = ref(import.meta.env.VITE_TITLE)
const version = ref(import.meta.env.VITE_VERSION)
const samples = ref([
"用小学生都能听懂的术语解释什么是量子纠缠",
"能给一位6岁男孩的生日会提供一些创造性的建议吗",
"如何用 Go 语言实现支持代理 Http client 请求?"
]);
'用小学生都能听懂的术语解释什么是量子纠缠',
'能给一位6岁男孩的生日会提供一些创造性的建议吗',
'如何用 Go 语言实现支持代理 Http client 请求?',
])
const plugins = ref([
{
value: "今日早报",
text: "今日早报:获取当天全球的热门新闻事件列表"
value: '今日早报',
text: '今日早报:获取当天全球的热门新闻事件列表',
},
{
value: "微博热搜",
text: "微博热搜:新浪微博热搜榜,微博当日热搜榜单"
value: '微博热搜',
text: '微博热搜:新浪微博热搜榜,微博当日热搜榜单',
},
{
value: "今日头条",
text: "今日头条:给用户推荐当天的头条新闻,周榜热文"
}
]);
value: '今日头条',
text: '今日头条:给用户推荐当天的头条新闻,周榜热文',
},
])
const capabilities = ref([
{
text: "轻松扮演翻译专家程序员AI 女友,文案高手...",
value: ""
text: '轻松扮演翻译专家程序员AI 女友,文案高手...',
value: '',
},
{
text: "国产大语言模型支持百度文心科大讯飞ChatGLM...",
value: ""
text: '国产大语言模型支持百度文心科大讯飞ChatGLM...',
value: '',
},
{
text: "绘画马斯克开拖拉机20世纪中国农村。3:2",
value: "绘画马斯克开拖拉机20世纪中国农村。3:2"
}
]);
text: '绘画马斯克开拖拉机20世纪中国农村。3:2',
value: '绘画马斯克开拖拉机20世纪中国农村。3:2',
},
])
onMounted(() => {
getSystemInfo()
.then((res) => {
title.value = res.data.title;
title.value = res.data.title
})
.catch((e) => {
ElMessage.error("获取系统配置失败:" + e.message);
});
});
ElMessage.error('获取系统配置失败:' + e.message)
})
})
const emits = defineEmits(["send"]);
const emits = defineEmits(['send'])
const send = (text) => {
emits("send", text);
};
emits('send', text)
}
</script>
<style scoped lang="stylus">
.welcome {

View File

@@ -12,14 +12,22 @@
<div class="breadcrumb">
<el-breadcrumb :separator-icon="ArrowRight">
<el-breadcrumb-item v-for="item in breadcrumb" :key="item.title">{{ item.title }}</el-breadcrumb-item>
<el-breadcrumb-item v-for="item in breadcrumb" :key="item.title">{{
item.title
}}</el-breadcrumb-item>
</el-breadcrumb>
</div>
<div class="header-right">
<div class="header-user-con">
<!-- 切换主题 -->
<el-switch style="margin-right: 10px" v-model="dark" inline-prompt :active-action-icon="Moon"
:inactive-action-icon="Sunny" @change="changeTheme"/>
<el-switch
style="margin-right: 10px"
v-model="dark"
inline-prompt
:active-action-icon="Moon"
:inactive-action-icon="Sunny"
@change="changeTheme"
/>
<!-- 用户名下拉菜单 -->
<el-dropdown class="user-name" :hide-on-click="true" trigger="click">
<span class="el-dropdown-link">
@@ -30,7 +38,9 @@
</span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item><i class="iconfont icon-version"></i> 当前版本{{ version }}</el-dropdown-item>
<el-dropdown-item
><i class="iconfont icon-version"></i> 当前版本{{ version }}</el-dropdown-item
>
<el-dropdown-item divided @click="logout">
<i class="iconfont icon-logout"></i>
<span>退出登录</span>
@@ -43,103 +53,103 @@
</div>
</template>
<script setup>
import {onMounted, ref, watch} from "vue";
import {getMenuItems, useSidebarStore} from "@/store/sidebar";
import {useRouter} from "vue-router";
import {ArrowDown, ArrowRight, Expand, Fold, Moon, Sunny} from "@element-plus/icons-vue";
import {httpGet} from "@/utils/http";
import {ElMessage} from "element-plus";
import {removeAdminToken} from "@/store/session";
import {useSharedStore} from "@/store/sharedata";
import { removeAdminToken } from '@/store/session'
import { useSharedStore } from '@/store/sharedata'
import { getMenuItems, useSidebarStore } from '@/store/sidebar'
import { httpGet } from '@/utils/http'
import { ArrowDown, ArrowRight, Expand, Fold, Moon, Sunny } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
const version = ref(process.env.VUE_APP_VERSION);
const avatar = ref("/images/user-info.jpg");
const sidebar = useSidebarStore();
const router = useRouter();
const breadcrumb = ref([]);
const version = ref(import.meta.env.VITE_VERSION)
const avatar = ref('/images/user-info.jpg')
const sidebar = useSidebarStore()
const router = useRouter()
const breadcrumb = ref([])
const store = useSharedStore();
const dark = ref(store.theme === "dark");
const theme = ref(store.theme);
const store = useSharedStore()
const dark = ref(store.theme === 'dark')
const theme = ref(store.theme)
watch(
() => store.theme,
() => store.theme,
(val) => {
theme.value = val;
theme.value = val
}
);
)
const changeTheme = () => {
store.setTheme(dark.value ? "dark" : "light");
};
store.setTheme(dark.value ? 'dark' : 'light')
}
router.afterEach((to) => {
initBreadCrumb(to.path);
});
initBreadCrumb(to.path)
})
onMounted(() => {
initBreadCrumb(router.currentRoute.value.path);
});
initBreadCrumb(router.currentRoute.value.path)
})
// 初始化面包屑导航
const initBreadCrumb = (path) => {
breadcrumb.value = [{ title: "首页" }];
const items = getMenuItems();
breadcrumb.value = [{ title: '首页' }]
const items = getMenuItems()
if (items) {
let bk = false;
let bk = false
for (let i = 0; i < items.length; i++) {
if (items[i].index === path) {
breadcrumb.value.push({
title: items[i].title,
path: items[i].index,
});
break;
})
break
}
if (bk) {
break;
break
}
if (items[i]["subs"]) {
const subs = items[i]["subs"];
if (items[i]['subs']) {
const subs = items[i]['subs']
for (let j = 0; j < subs.length; j++) {
if (subs[j].index === path) {
breadcrumb.value.push({
title: items[i].title,
path: items[i].index,
});
})
breadcrumb.value.push({
title: subs[j].title,
path: subs[j].index,
});
bk = true;
break;
})
bk = true
break
}
}
}
}
}
};
}
// 侧边栏折叠
const collapseChange = () => {
sidebar.handleCollapse();
};
sidebar.handleCollapse()
}
onMounted(() => {
if (document.body.clientWidth < 1024) {
collapseChange();
collapseChange()
}
});
})
const logout = function () {
httpGet("/api/admin/logout")
httpGet('/api/admin/logout')
.then(() => {
removeAdminToken();
router.replace("/admin/login");
removeAdminToken()
router.replace('/admin/login')
})
.catch((e) => {
ElMessage.error("注销失败: " + e.message);
});
};
ElMessage.error('注销失败: ' + e.message)
})
}
</script>
<style scoped lang="stylus">
.admin-header {