mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
304 lines
8.8 KiB
JavaScript
304 lines
8.8 KiB
JavaScript
(() => {
|
|
let Room;
|
|
let createLocalTracks;
|
|
let RoomEvent;
|
|
let Track;
|
|
let room = null;
|
|
let visualizerTimer = null;
|
|
|
|
const startBtn = document.getElementById('startBtn');
|
|
const stopBtn = document.getElementById('stopBtn');
|
|
const statusText = document.getElementById('statusText');
|
|
const logContainer = document.getElementById('log');
|
|
const voiceSelect = document.getElementById('voiceSelect');
|
|
const personalitySelect = document.getElementById('personalitySelect');
|
|
const speedRange = document.getElementById('speedRange');
|
|
const speedValue = document.getElementById('speedValue');
|
|
const statusVoice = document.getElementById('statusVoice');
|
|
const statusPersonality = document.getElementById('statusPersonality');
|
|
const statusSpeed = document.getElementById('statusSpeed');
|
|
const audioRoot = document.getElementById('audioRoot');
|
|
const copyLogBtn = document.getElementById('copyLogBtn');
|
|
const clearLogBtn = document.getElementById('clearLogBtn');
|
|
const visualizer = document.getElementById('visualizer');
|
|
|
|
function log(message, level = 'info') {
|
|
if (!logContainer) {
|
|
return;
|
|
}
|
|
const p = document.createElement('p');
|
|
const time = new Date().toLocaleTimeString();
|
|
p.textContent = `[${time}] ${message}`;
|
|
if (level === 'error') {
|
|
p.classList.add('log-error');
|
|
} else if (level === 'warn') {
|
|
p.classList.add('log-warn');
|
|
}
|
|
logContainer.prepend(p);
|
|
if (typeof console !== 'undefined') {
|
|
console.log(message);
|
|
}
|
|
}
|
|
|
|
function toast(message, type) {
|
|
if (typeof showToast === 'function') {
|
|
showToast(message, type);
|
|
} else {
|
|
log(message, type === 'error' ? 'error' : 'info');
|
|
}
|
|
}
|
|
|
|
function setStatus(state, text) {
|
|
if (!statusText) {
|
|
return;
|
|
}
|
|
statusText.textContent = text;
|
|
statusText.classList.remove('connected', 'connecting', 'error');
|
|
if (state) {
|
|
statusText.classList.add(state);
|
|
}
|
|
}
|
|
|
|
function setButtons(connected) {
|
|
if (!startBtn || !stopBtn) {
|
|
return;
|
|
}
|
|
if (connected) {
|
|
startBtn.classList.add('hidden');
|
|
stopBtn.classList.remove('hidden');
|
|
} else {
|
|
startBtn.classList.remove('hidden');
|
|
stopBtn.classList.add('hidden');
|
|
startBtn.disabled = false;
|
|
}
|
|
}
|
|
|
|
function updateMeta() {
|
|
if (statusVoice) {
|
|
statusVoice.textContent = voiceSelect.value;
|
|
}
|
|
if (statusPersonality) {
|
|
statusPersonality.textContent = personalitySelect.value;
|
|
}
|
|
if (statusSpeed) {
|
|
statusSpeed.textContent = `${speedRange.value}x`;
|
|
}
|
|
}
|
|
|
|
function initLiveKit() {
|
|
const lk = window.LiveKitClient || window.LivekitClient;
|
|
if (!lk) {
|
|
return false;
|
|
}
|
|
Room = lk.Room;
|
|
createLocalTracks = lk.createLocalTracks;
|
|
RoomEvent = lk.RoomEvent;
|
|
Track = lk.Track;
|
|
return true;
|
|
}
|
|
|
|
function ensureLiveKit() {
|
|
if (Room) {
|
|
return true;
|
|
}
|
|
if (!initLiveKit()) {
|
|
log(t('voice.livekitSDKError'), 'error');
|
|
toast(t('voice.livekitLoadFailed'), 'error');
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function ensureMicSupport() {
|
|
const hasMediaDevices = typeof navigator !== 'undefined' && navigator.mediaDevices;
|
|
const hasGetUserMedia = hasMediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function';
|
|
if (hasGetUserMedia) {
|
|
return true;
|
|
}
|
|
const isLocalhost = ['localhost', '127.0.0.1'].includes(window.location.hostname);
|
|
const secureHint = window.isSecureContext || isLocalhost
|
|
? t('voice.secureContextBrowser')
|
|
: t('voice.secureContextHTTPS');
|
|
throw new Error(t('voice.secureContextError', { hint: secureHint }));
|
|
}
|
|
|
|
async function startSession() {
|
|
if (!ensureLiveKit()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const authHeader = await ensureFunctionKey();
|
|
if (authHeader === null) {
|
|
toast(t('common.configurePublicKey'), 'error');
|
|
window.location.href = '/login';
|
|
return;
|
|
}
|
|
|
|
startBtn.disabled = true;
|
|
updateMeta();
|
|
setStatus('connecting', t('voice.connectingStatus'));
|
|
log(t('voice.fetchingToken'));
|
|
|
|
const params = new URLSearchParams({
|
|
voice: voiceSelect.value,
|
|
personality: personalitySelect.value,
|
|
speed: speedRange.value
|
|
});
|
|
|
|
const headers = buildAuthHeaders(authHeader);
|
|
|
|
const response = await fetch(`/v1/function/voice/token?${params.toString()}`, {
|
|
headers
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(t('voice.fetchTokenFailed', { status: response.status }));
|
|
}
|
|
|
|
const { token, url } = await response.json();
|
|
log(`${t('voice.fetchTokenSuccess')} (${voiceSelect.value}, ${personalitySelect.value}, ${speedRange.value}x)`);
|
|
|
|
room = new Room({
|
|
adaptiveStream: true,
|
|
dynacast: true
|
|
});
|
|
|
|
room.on(RoomEvent.ParticipantConnected, (p) => log(t('voice.participantConnected', { identity: p.identity })));
|
|
room.on(RoomEvent.ParticipantDisconnected, (p) => log(t('voice.participantDisconnected', { identity: p.identity })));
|
|
room.on(RoomEvent.TrackSubscribed, (track) => {
|
|
log(t('voice.trackSubscribed', { kind: track.kind }));
|
|
if (track.kind === Track.Kind.Audio) {
|
|
const element = track.attach();
|
|
if (audioRoot) {
|
|
audioRoot.appendChild(element);
|
|
} else {
|
|
document.body.appendChild(element);
|
|
}
|
|
}
|
|
});
|
|
|
|
room.on(RoomEvent.Disconnected, () => {
|
|
log(t('voice.disconnected'));
|
|
resetUI();
|
|
});
|
|
|
|
await room.connect(url, token);
|
|
log(t('voice.connectedToServer'));
|
|
|
|
setStatus('connected', t('voice.inCall'));
|
|
setButtons(true);
|
|
|
|
log(t('voice.openingMic'));
|
|
ensureMicSupport();
|
|
const tracks = await createLocalTracks({ audio: true, video: false });
|
|
for (const track of tracks) {
|
|
await room.localParticipant.publishTrack(track);
|
|
}
|
|
log(t('voice.voiceEnabled'));
|
|
toast(t('voice.voiceConnected'), 'success');
|
|
} catch (err) {
|
|
const message = err && err.message ? err.message : t('common.connectionFailed');
|
|
log(t('voice.errorPrefix', { msg: message }), 'error');
|
|
toast(message, 'error');
|
|
setStatus('error', t('common.connectionError'));
|
|
startBtn.disabled = false;
|
|
}
|
|
}
|
|
|
|
async function stopSession() {
|
|
if (room) {
|
|
await room.disconnect();
|
|
}
|
|
resetUI();
|
|
}
|
|
|
|
function resetUI() {
|
|
setStatus('', t('common.notConnected'));
|
|
setButtons(false);
|
|
if (audioRoot) {
|
|
audioRoot.innerHTML = '';
|
|
}
|
|
}
|
|
|
|
function clearLog() {
|
|
if (logContainer) {
|
|
logContainer.innerHTML = '';
|
|
}
|
|
}
|
|
|
|
async function copyLog() {
|
|
if (!logContainer) {
|
|
return;
|
|
}
|
|
const lines = Array.from(logContainer.querySelectorAll('p'))
|
|
.map((p) => p.textContent)
|
|
.join('\n');
|
|
try {
|
|
await navigator.clipboard.writeText(lines);
|
|
toast(t('voice.logCopied'), 'success');
|
|
} catch (err) {
|
|
toast(t('voice.copyLogFailed'), 'error');
|
|
}
|
|
}
|
|
|
|
speedRange.addEventListener('input', (e) => {
|
|
speedValue.textContent = Number(e.target.value).toFixed(1);
|
|
const min = Number(speedRange.min || 0);
|
|
const max = Number(speedRange.max || 100);
|
|
const val = Number(speedRange.value || 0);
|
|
const pct = ((val - min) / (max - min)) * 100;
|
|
speedRange.style.setProperty('--range-progress', `${pct}%`);
|
|
updateMeta();
|
|
});
|
|
|
|
voiceSelect.addEventListener('change', updateMeta);
|
|
personalitySelect.addEventListener('change', updateMeta);
|
|
|
|
startBtn.addEventListener('click', startSession);
|
|
stopBtn.addEventListener('click', stopSession);
|
|
if (copyLogBtn) {
|
|
copyLogBtn.addEventListener('click', copyLog);
|
|
}
|
|
if (clearLogBtn) {
|
|
clearLogBtn.addEventListener('click', clearLog);
|
|
}
|
|
|
|
speedValue.textContent = Number(speedRange.value).toFixed(1);
|
|
{
|
|
const min = Number(speedRange.min || 0);
|
|
const max = Number(speedRange.max || 100);
|
|
const val = Number(speedRange.value || 0);
|
|
const pct = ((val - min) / (max - min)) * 100;
|
|
speedRange.style.setProperty('--range-progress', `${pct}%`);
|
|
}
|
|
function buildVisualizerBars() {
|
|
if (!visualizer) return;
|
|
visualizer.innerHTML = '';
|
|
const targetCount = Math.max(36, Math.floor(visualizer.offsetWidth / 7));
|
|
for (let i = 0; i < targetCount; i += 1) {
|
|
const bar = document.createElement('div');
|
|
bar.className = 'bar';
|
|
visualizer.appendChild(bar);
|
|
}
|
|
}
|
|
|
|
window.addEventListener('resize', buildVisualizerBars);
|
|
buildVisualizerBars();
|
|
updateMeta();
|
|
setStatus('', t('common.notConnected'));
|
|
|
|
if (!visualizerTimer) {
|
|
visualizerTimer = setInterval(() => {
|
|
const bars = document.querySelectorAll('.visualizer .bar');
|
|
bars.forEach((bar) => {
|
|
if (statusText && statusText.classList.contains('connected')) {
|
|
bar.style.height = `${Math.random() * 32 + 6}px`;
|
|
} else {
|
|
bar.style.height = '6px';
|
|
}
|
|
});
|
|
}, 150);
|
|
}
|
|
})();
|