UNPKG

trtc-sdk-v5

Version:
1 lines 6.07 kB
var __defProp=Object.defineProperty,__defNormalProp=(r,e,t)=>e in r?__defProp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,__publicField=(r,e,t)=>__defNormalProp(r,"symbol"!=typeof e?e+"":e,t),StartValidateRule={name:"option",required:!0,properties:{sourceLanguage:{type:"string",required:!0},translationLanguages:{type:["string","array"],required:!1},userIdsToTranscribe:{type:["string","array"],required:!1},transcriberRobotId:{type:"string",required:!1}}},StopValidateRule={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},STOP_IGNORE_CODES=new Set([2002,4003]),STOP_RETRYABLE_CODES=new Set([3e3]),STOP_MAX_RETRIES=2,STOP_RETRY_DELAY=1e3,delay=r=>new Promise(e=>setTimeout(e,r)),STORAGE_KEY_PREFIX="TRTC_RT_",_RealtimeTranscriber=class r{constructor(r){this.core=r,__publicField(this,"disableRandomCall",!0),__publicField(this,"activeTranscriberMap",new Map),__publicField(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return r.Name}getAlias(){return"rt-trans"}getStorageKey(){return`${STORAGE_KEY_PREFIX}${this.core.room.userId}`}saveToStorage(){try{const r={};this.activeTranscriberMap.forEach((e,t)=>{r[t]=e}),localStorage.setItem(this.getStorageKey(),JSON.stringify(r))}catch(r){}}loadFromStorage(){try{const r=localStorage.getItem(this.getStorageKey());if(!r)return null;const e=JSON.parse(r);if(!e||"object"!=typeof e)return this.removeFromStorage(),null;const t=new Map;for(const[r,o]of Object.entries(e))o&&"object"==typeof o&&"taskId"in o&&t.set(r,o);return t}catch(r){return this.removeFromStorage(),null}}removeFromStorage(){try{localStorage.removeItem(this.getStorageKey())}catch(r){}}getGroup(){return"*"}getValidateRule(r){switch(r){case"start":return StartValidateRule;case"update":return{};case"stop":return StopValidateRule}}async start(r){var e;const{RtcError:t,ErrorCode:o}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new t({code:o.ENV_NOT_SUPPORTED});const{sourceLanguage:a,translationLanguages:s,userIdsToTranscribe:i="all",transcriberRobotId:n}=r,d=n||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,c={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:d,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:a,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};s&&s.length>0&&(c.translationParams.mode=1,c.translationParams.targetLangs=Array.isArray(s)?s:[s]),"all"===i?c.subscribeParams.subUsers=[]:Array.isArray(i)?c.subscribeParams.subUsers=i.map(r=>({userId:r,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):i&&(c.subscribeParams.subUsers=[{userId:i,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(c)}`);const a=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:c,retries:0}),{code:s,data:i}=a.data;if(0!==s){const r=(null==(e=a.data)?void 0:e.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:s,reason:r,data:i}),new t({code:o.SERVER_ERROR,extraCode:s,message:r})}const{taskId:n}=i;if(!n)throw this._log.error("taskId is required",{data:a.data}),new t({code:o.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(d,{taskId:n,options:r}),this.saveToStorage(),this._log.info(`start_cloud_transcription success robotId: ${d}, taskId: ${n}, activeSize: ${this.activeTranscriberMap.size}`),d}catch(r){throw this._log.error("start_cloud_transcription failed",{error:r}),r}}async update(){}async sendStopSignal(r){var e;const{RtcError:t,ErrorCode:o}=this.core.errorModule,a=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:r},retries:3});if(0!==a.data.code){const r=a.data.code,s=(null==(e=a.data)?void 0:e.message)||"";if(STOP_IGNORE_CODES.has(r))return void this._log.warn("stop_cloud_transcription ignored error",{extraCode:r,reason:s,data:a.data.data});if(STOP_RETRYABLE_CODES.has(r)){const e=new t({code:o.SERVER_ERROR,extraCode:r,message:s});throw e.retryable=!0,e}throw this._log.error("stop_cloud_transcription failed",{extraCode:r,reason:s,data:a.data.data}),new t({code:o.SERVER_ERROR,extraCode:r,message:s})}}async stopWithRetry(r){const{RtcError:e,ErrorCode:t}=this.core.errorModule,o=STOP_MAX_RETRIES+1;let a;for(let e=1;e<=o;e++)try{return await this.sendStopSignal(r),void(e>1&&this._log.info(`stop_cloud_transcription succeeded after ${e-1} retries`))}catch(r){if(a=r,!r.retryable||e>=o)break;this._log.warn(`stop_cloud_transcription retryable error, retry ${e}/${STOP_MAX_RETRIES}`,{extraCode:r.extraCode,message:r.message}),await delay(STOP_RETRY_DELAY)}const s=null==a?void 0:a.extraCode,i=(null==a?void 0:a.message)||"";if(null==a?void 0:a.retryable){const r=`stop_cloud_transcription failed after ${STOP_MAX_RETRIES} retries: ${i}. Please try again later.`;throw this._log.error(r,{extraCode:s,totalAttempts:STOP_MAX_RETRIES+1}),new e({code:t.SERVER_ERROR,extraCode:s,message:r})}throw a}async stop({transcriberRobotId:r}){const{RtcError:e,ErrorCode:t}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new e({code:t.ENV_NOT_SUPPORTED});let o=this.activeTranscriberMap.get(r);if(!o){const e=this.loadFromStorage();e&&(o=e.get(r))}const a=(null==o?void 0:o.taskId)||r;this._log.info(`stop_cloud_transcription taskId: ${a}`);try{await this.stopWithRetry(a)}catch(r){throw this._log.error("stop_cloud_transcription failed",{error:r}),r}finally{this.activeTranscriberMap.delete(r),0===this.activeTranscriberMap.size?this.removeFromStorage():this.saveToStorage()}}destroy(){this.activeTranscriberMap.clear(),this.removeFromStorage()}};__publicField(_RealtimeTranscriber,"Name","RealtimeTranscriber");var RealtimeTranscriber=_RealtimeTranscriber,index_default=RealtimeTranscriber;export{index_default as default};export{RealtimeTranscriber};