100 lines
2.6 KiB
TypeScript
Raw Normal View History

import { rtcConfig } from 'config/rtcConfig'
import { parseCandidate } from 'sdp'
export enum ConnectionTestEvents {
CONNECTION_TEST_RESULTS_UPDATED = 'CONNECTION_TEST_RESULTS_UPDATED',
HAS_HOST_CHANGED = 'HAS_HOST_CHANGED',
HAS_RELAY_CHANGED = 'HAS_RELAY_CHANGED',
}
export type ConnectionTestEvent = CustomEvent<ConnectionTest>
2023-03-28 09:24:06 -05:00
const checkExperationTime = 10 * 1000
export class ConnectionTest extends EventTarget {
hasHost = false
hasRelay = false
hasPeerReflexive = false
hasServerReflexive = false
2023-03-28 09:13:35 -05:00
rtcPeerConnection?: RTCPeerConnection
async runRtcPeerConnectionTest() {
if (typeof RTCPeerConnection === 'undefined') return
const { iceServers } = rtcConfig
2023-03-28 09:13:35 -05:00
this.rtcPeerConnection = new RTCPeerConnection({
iceServers,
})
2023-03-28 09:24:06 -05:00
const hasHostCheckTimeout = setTimeout(() => {
this.hasHost = false
this.dispatchEvent(
new CustomEvent(ConnectionTestEvents.HAS_HOST_CHANGED, {
detail: this,
})
)
}, checkExperationTime)
const hasRelayCheckTimeout = setTimeout(() => {
this.hasRelay = false
this.dispatchEvent(
new CustomEvent(ConnectionTestEvents.HAS_RELAY_CHANGED, {
detail: this,
})
)
}, checkExperationTime)
2023-03-28 09:13:35 -05:00
this.rtcPeerConnection.addEventListener('icecandidate', event => {
if (event.candidate?.candidate.length) {
const parsedCandidate = parseCandidate(event.candidate.candidate)
let eventType: ConnectionTestEvents | undefined
switch (parsedCandidate.type) {
case 'host':
2023-03-28 09:24:06 -05:00
clearTimeout(hasHostCheckTimeout)
this.hasHost = window.navigator.onLine
eventType = ConnectionTestEvents.HAS_HOST_CHANGED
break
case 'relay':
2023-03-28 09:24:06 -05:00
clearTimeout(hasRelayCheckTimeout)
this.hasRelay = window.navigator.onLine
eventType = ConnectionTestEvents.HAS_RELAY_CHANGED
break
}
if (typeof eventType !== 'undefined') {
this.dispatchEvent(
new CustomEvent(eventType, {
detail: this,
})
)
}
this.dispatchEvent(
new Event(ConnectionTestEvents.CONNECTION_TEST_RESULTS_UPDATED)
)
}
})
// Kick off the connection test
try {
2023-03-28 09:13:35 -05:00
const rtcSessionDescription = await this.rtcPeerConnection.createOffer({
offerToReceiveAudio: true,
})
2023-03-28 09:13:35 -05:00
this.rtcPeerConnection.setLocalDescription(rtcSessionDescription)
} catch (e) {}
}
2023-03-28 09:13:35 -05:00
destroy() {
this.rtcPeerConnection?.close()
}
}
export const connectionTest = new ConnectionTest()