import { VoiceStateUpdateSchema } from "../schema/VoiceStateUpdateSchema" ; import { Payload , WebSocket } from "@fosscord/gateway" ; import { genVoiceToken } from "../util/SessionUtils" ; import { check } from "./instanceOf" ; import { Config , emitEvent , Guild , Member , Region , VoiceServerUpdateEvent , VoiceState , VoiceStateUpdateEvent , } from "@fosscord/util" ; export async function onVoiceStateUpdate ( this , data ) { check . call ( this , VoiceStateUpdateSchema , data . d ) ; const body = data . d as VoiceStateUpdateSchema ; let voiceState ; try { voiceState = await VoiceState . findOneOrFail ( { where : { user_id : this . user_id } , } ) ; if ( voiceState . session_id !== this . session_id && body . channel_id === null ) { return ; } if ( voiceState . guild_id !== body . guild_id && voiceState . session_id === this . session_id ) { await emitEvent ( { event : "VOICE_STATE_UPDATE" , data : { ... voiceState , channel_id : null } , guild_id : voiceState . guild_id , } ) ; } if ( body . guild_id === null ) body . guild_id = voiceState . guild_id ; voiceState . assign ( body ) ; } catch ( error ) { voiceState = new VoiceState ( { ... body , user_id : this . user_id , deaf : false , mute : false , suppress : false , } ) ; } voiceState . member = await Member . findOneOrFail ( { where : { id : voiceState . user_id , guild_id : voiceState . guild_id } , relations : [ "user" , "roles" ] , } ) ; if ( voiceState . session_id !== this . session_id ) voiceState . token = genVoiceToken ( ) ; voiceState . session_id = this . session_id ; const { id , ... newObj } = voiceState ; await Promise . all ( [ voiceState . save ( ) , emitEvent ( { event : "VOICE_STATE_UPDATE" , data : newObj , guild_id : voiceState . guild_id , } as VoiceStateUpdateEvent ) , ] ) ; if ( voiceState . channel_id !== null ) { const guild = await Guild . findOne ( { id : voiceState . guild_id } ) ; const regions = Config . get ( ) . regions ; let guildRegion ; if ( guild && guild . region ) { guildRegion = regions . available . filter ( ( r ) => r . id === guild . region ) [ 0 ] ; } else { guildRegion = regions . available . filter ( ( r ) => r . id === regions . default ) [ 0 ] ; } await emitEvent ( { event : "VOICE_SERVER_UPDATE" , data : { token : voiceState . token , guild_id : voiceState . guild_id , endpoint : guildRegion . endpoint , } , guild_id : voiceState . guild_id , } as VoiceServerUpdateEvent ) ; } }