/* Independent teacher room: one automatic start, explicit restarts, no provider keys. */ (()=>{ 'use strict'; const $=id=>document.getElementById(id),portrait=$('portrait'),video=$('avatar'),status=$('status'),notice=$('notice'),budget=$('budget'),sendButton=$('send'),connectButton=$('connect'),endButton=$('end'),question=$('question'),messages=$('messages'); let current=null,serial=0,sdkPromise=null,sound=true,busy=false,pending=null,autoStarted=false,disposing=Promise.resolve(); const api='/api/teacher/'; let mic=null; function setStatus(text,on=false){status.textContent=text;$('dot').classList.toggle('on',on)} function send(c,d){if(c?.ws?.readyState!==1)throw Error('连接已结束');c.ws.send(JSON.stringify(d))} function sdk(){ if(window.AliRtcEngine)return Promise.resolve(); if(!sdkPromise)sdkPromise=new Promise((resolve,reject)=>{ const el=document.createElement('script');el.src='https://g.alicdn.com/apsara-media-box/imp-web-rtc/7.1.9/aliyun-rtc-sdk.js'; el.onload=()=>window.AliRtcEngine?resolve():reject(Error('视频组件不可用'));el.onerror=()=>reject(Error('视频组件未能加载'));document.head.append(el); });return sdkPromise; } function controls(){sendButton.disabled=!current?.ready||current.closed||busy||!!mic?.active;endButton.disabled=!current||current.closed;connectButton.hidden=!!current&&!current.closed;mic?.update();$('sound').disabled=!!mic?.recording} function release(c){ if(c.released)return;c.released=true;portrait.classList.remove('live');video.srcObject=null; if(c.engine){ try{c.engine.subscribeAllRemoteAudioStreams(false)}catch{} disposing=Promise.resolve(c.engine.leaveChannel()).catch(()=>{}).finally(()=>{try{c.engine.destroy()}catch{}}); } } function beacon(c){ if(!c?.id)return; const data=JSON.stringify({id:c.id}); try{if(navigator.sendBeacon(api+'stop',new Blob([data],{type:'application/json'})))return}catch{} fetch(api+'stop',{method:'POST',headers:{'Content-Type':'application/json'},body:data,credentials:'same-origin',keepalive:true}).catch(()=>{}); } function stop(reason='user'){ mic?.cancel(''); const c=current;if(!c||c.closed)return; c.closed=true;c.ready=false;busy=false;clearTimeout(c.startTimer);clearInterval(c.heartbeat); try{send(c,{type:'stop'})}catch{} beacon(c);release(c); setStatus('正在结束连接');budget.textContent='正在确认数字人已停止';notice.textContent='文字和输入草稿已保留。'; controls();connectButton.disabled=true; c.closeTimer=setTimeout(()=>{ try{c.ws?.close()}catch{} if(current===c){setStatus('连接已断开');budget.textContent='结束状态尚未确认';notice.textContent='服务端正在清理本场,请稍后刷新确认。';connectButton.disabled=true} },55000); if(!c.startSent){try{c.ws?.close()}catch{}clearTimeout(c.closeTimer);current=null;setStatus('尚未建立连接');budget.textContent='未开始生成';connectButton.disabled=false;controls()} } function failed(c,message){ if(current!==c)return; notice.textContent=message;stop('error'); notice.textContent=message+';已请求结束本场。'; } function terminal(c,d){ if(current===c)mic?.cancel(''); clearTimeout(c.closeTimer);clearTimeout(c.startTimer);clearInterval(c.heartbeat); c.closed=true;c.ready=false;release(c);try{c.ws?.close()}catch{} if(current!==c)return; busy=false;current=null;controls();connectButton.disabled=!d.confirmed; const labels={idle_timeout:'空闲 60 秒,已断开',browser_lost:'连接中断,已结束',page_closed:'页面离开,已结束',session_limit:'本场已达 5 分钟',user_end:'本场对话已结束',browser_disconnected:'本场对话已结束'}; setStatus(d.confirmed?(labels[d.reason]||'本场对话已结束'):'结束状态待确认'); budget.textContent=d.confirmed?'数字人已停止生成':'未自动重连'; notice.textContent=d.confirmed?'可以编辑问题,点击“继续对话”重新连接。':'上游尚未确认结束,暂不创建新会话。'; } function greet(c){ if(current!==c||c.closed||!c.ready||!c.greetingEnabled||c.userStarted)return; if(!c.greetingShown){c.greetingShown=true;c.greetingNode=addMessage('assistant',c.greetingText)} if(c.greetingSent||busy||mic?.active)return; if(!sound){notice.textContent='可打字或用麦克风交流;点击“开启声音”听开场介绍。';return} c.greetingSent=true;c.greetingBusy=true;busy=true;controls(); setStatus('老师正在介绍',true);notice.textContent='老师正在做简短介绍…'; try{send(c,{type:'greeting'})}catch{c.greetingBusy=false;busy=false;controls();notice.textContent='开场语音未能开始,可以直接输入问题。'} } async function join(c,rtc){ await disposing;if(c.closed)return; const engine=AliRtcEngine.getInstance();c.engine=engine; engine.on('videoSubscribeStateChanged',(uid,old,next)=>{ if(c.closed||current!==c)return; if(next===3){ engine.setRemoteViewConfig(video,uid,1); video.play().catch(()=>{notice.textContent='点击画面播放视频';}); } }); video.onplaying=()=>{if(current===c&&!c.closed&&!c.ready){portrait.classList.add('live');c.ready=true;clearTimeout(c.startTimer);setStatus('老师已就位',true);notice.textContent='可以打字或点击麦克风交流。';controls();greet(c)}}; for(const name of ['occurError','bye','remoteVideoPlayError'])engine.on(name,()=>failed(c,'视频连接中断')); for(const name of ['remoteAudioAutoPlayFail','remoteAudioPlayError'])engine.on(name,()=>{if(current===c&&!c.closed){sound=false;updateSound();notice.textContent='浏览器限制声音自动播放,请点击“开启声音”。'}}); engine.on('remoteVideoAutoPlayFail',()=>{notice.textContent='请点击画面播放视频。'}); await engine.publishLocalAudioStream(false);await engine.publishLocalVideoStream(false); engine.setDefaultSubscribeAllRemoteAudioStreams(sound&&!mic?.recording);engine.setDefaultSubscribeAllRemoteVideoStreams(true); if(c.closed)return; await engine.joinChannel(rtc.token,rtc.user_id); if(c.closed){try{await engine.leaveChannel();engine.destroy()}catch{}} } function addMessage(role,text){ $('welcome')?.remove(); const row=document.createElement('div');row.className='message '+role; const label=document.createElement('b');label.textContent=role==='user'?'你':'知微老师'; const content=document.createElement('span');content.textContent=text;row.append(label,content);messages.append(row); while(messages.children.length>24)messages.firstElementChild.remove(); messages.scrollTop=messages.scrollHeight;return content; } function event(c,d){ if(d.type==='session'){c.id=d.id;if(c.closed)beacon(c);return} if(d.type==='stopped'){terminal(c,d);return} if(c.closed||current!==c)return; if(d.type==='ready'){join(c,d.rtc).catch(()=>failed(c,'无法加入实时画面'));return} if(d.type==='budget'){ budget.textContent=d.remaining===null?'老师正在回答 · 本场剩余 '+d.maximum_remaining+' 秒':'空闲 '+d.remaining+' 秒后断开'; return; } if(d.type==='error'){ if(!c.id){clearTimeout(c.startTimer);clearInterval(c.heartbeat);c.closed=true;try{c.ws.close()}catch{}current=null;busy=false;setStatus('暂未连接');notice.textContent=d.message||'数字人暂不可用';budget.textContent='本次没有创建会话';controls();connectButton.disabled=false} else failed(c,d.message||'数字人暂不可用');return; } if(d.type==='greeting'){ if(!c.greetingShown){c.greetingShown=true;c.greetingNode=addMessage('assistant',d.text)} else if(c.greetingNode)c.greetingNode.textContent=d.text; return; } if(d.type==='greeting_done'){ if(c.greetingBusy){c.greetingBusy=false;busy=false;controls();setStatus('老师已就位',true); notice.textContent=d.message||(sound?'可以打字或点击麦克风开始交流。':'浏览器限制自动播放时,请点击“开启声音”后交流。');} return; } if(d.type==='drained'){setStatus('老师已就位',true);return} if(d.request_id!==pending?.id)return; if(d.type==='snapshot'||d.type==='answer'){ setStatus('老师正在回答',true); const near=messages.scrollHeight-messages.scrollTop-messages.clientHeight<45; pending.node.textContent=d.text;if(near)messages.scrollTop=messages.scrollHeight; if(d.type==='answer')notice.textContent=sound?'文字已完整返回,老师继续讲解。':'文字已完整返回,可开启声音听讲解。'; }else if(d.type==='thinking'){setStatus('老师正在思考',true);notice.textContent='正在组织回答…'} else if(d.type==='voice_error'){notice.textContent=d.message} else if(d.type==='chat_error'){pending.node.textContent=d.message;notice.textContent=d.message;busy=false;controls()} else if(d.type==='turn_done'){busy=false;controls()} } async function start(){ if(current&&!current.closed)return; const c={serial:++serial,closed:false,ready:false,id:null,engine:null};current=c;busy=false;controls();connectButton.disabled=false; setStatus('正在连接老师');notice.textContent='正在初始化实时数字人…';budget.textContent='空闲 60 秒自动断开'; c.startTimer=setTimeout(()=>failed(c,'初始化超时'),45000); try{ const response=await fetch(api+'config',{cache:'no-store',credentials:'same-origin'}); if(!response.ok)throw Error('服务暂不可用'); const cfg=await response.json();c.greetingEnabled=cfg.greeting?.enabled===true;c.greetingText=cfg.greeting?.text||'';mic?.configure(cfg.mic?.enabled);if(!cfg.enabled)throw Error('教师形象尚未准备完成'); await sdk();if(c.closed||document.hidden)return; if(!await AliRtcEngine.isSupported())throw Error('浏览器暂不支持实时视频'); if(c.closed)return; const url=new URL(api+'stream',location.href);url.protocol=location.protocol==='https:'?'wss:':'ws:'; const ws=new WebSocket(url);c.ws=ws; ws.onopen=()=>{ if(c.closed){ws.close();return} send(c,{type:'start'});c.startSent=true;c.heartbeat=setInterval(()=>{try{send(c,{type:'ping'})}catch{failed(c,'连接中断')}},2000); }; ws.onmessage=e=>{try{event(c,JSON.parse(e.data))}catch{failed(c,'连接数据异常')}}; ws.onerror=()=>failed(c,'连接中断'); ws.onclose=()=>{ clearInterval(c.heartbeat);clearTimeout(c.startTimer); if(!c.closed){mic?.cancel('');c.closed=true;release(c);busy=false;controls();setStatus('连接已断开');budget.textContent='服务端正在确认结束';notice.textContent='没有自动重连,请稍后手动继续。';connectButton.disabled=false} }; }catch(e){ if(c.closed)return; clearTimeout(c.startTimer);current=null;setStatus('暂未连接');notice.textContent=e.message;budget.textContent='没有自动重试';controls(); } } function updateSound(){ $('sound').textContent=sound?'关闭声音':'开启声音';$('sound').setAttribute('aria-pressed',String(sound)); if(current?.engine&&!current.closed){try{current.engine.subscribeAllRemoteAudioStreams(sound&&!mic?.recording)}catch{}} } $('sound').onclick=()=>{ sound=!sound;updateSound(); if(sound)for(const media of document.querySelectorAll('audio,video'))if(media.srcObject)media.play().catch(()=>{notice.textContent='声音播放受限,请再次点击开启声音。'}); if(sound&¤t)greet(current); }; function submitQuestion(text,{clearDraft=true,fromMic=false}={}){ text=text.trim();const c=current; if(!text||text.length>question.maxLength||document.hidden||!navigator.onLine||!c?.ready||c.closed||busy||mic?.active||c.ws?.readyState!==1)return false; // The original click starts capture; automatic submission may still need browser audio permission. sound=true;updateSound();for(const m of document.querySelectorAll('audio,video'))if(m.srcObject)m.play().catch(()=>{}); const rid=crypto.randomUUID(); try{send(c,{type:'question',request_id:rid,text})}catch{notice.textContent='连接已结束,问题尚未发送。';return false} c.userStarted=true;addMessage('user',text);pending={id:rid,node:addMessage('assistant','…')}; busy=true;if(clearDraft)question.value='';controls(); notice.textContent=fromMic?'语音已自动发送,正在等待老师回答…':'正在等待老师回答…';return true; } $('form').onsubmit=e=>{e.preventDefault();submitQuestion(question.value)}; question.onkeydown=e=>{if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing){e.preventDefault();$('form').requestSubmit()}}; mic=window.TeacherMic?.({input:question,button:$('mic'),cancelButton:$('mic-cancel'),message:notice, onFinal:text=>submitQuestion(text,{clearDraft:false,fromMic:true}), onChange:()=>{controls();updateSound()},canStart:()=>!!current?.ready&&!current.closed&&!busy}); endButton.onclick=()=>stop();connectButton.onclick=()=>start(); $('fullscreen').onclick=()=>{if(document.fullscreenElement)document.exitFullscreen?.();else portrait.requestFullscreen?.().catch(()=>{notice.textContent='当前浏览器不支持页面全屏。'})}; video.onclick=()=>video.play().catch(()=>{}); window.addEventListener('pagehide',()=>{stop('pagehide');try{current?.ws?.close()}catch{}}); document.addEventListener('visibilitychange',()=>{ if(document.hidden&&autoStarted)stop('hidden'); else if(!document.hidden&&!autoStarted){autoStarted=true;start()} }); updateSound(); if(!document.hidden){autoStarted=true;start()} })();