11import { useRef , useCallback , useState } from 'react' ;
2- import { RTC_CONFIG } from '../config' ;
2+ import { fetchIceServers } from '../config' ;
33
44export interface PeerConnection {
55 peerConnection : RTCPeerConnection ;
@@ -19,6 +19,7 @@ export const useWebRTC = (options?: UseWebRTCOptions) => {
1919 const screenStreamRef = useRef < MediaStream | null > ( null ) ;
2020 const originalVideoTrackRef = useRef < MediaStreamTrack | null > ( null ) ;
2121 const [ isScreenSharing , setIsScreenSharing ] = useState ( false ) ;
22+ const iceServersRef = useRef < RTCIceServer [ ] | null > ( null ) ;
2223
2324 const initializeLocalStream = useCallback ( async ( ) : Promise < boolean > => {
2425 try {
@@ -39,8 +40,15 @@ export const useWebRTC = (options?: UseWebRTCOptions) => {
3940 }
4041 } , [ ] ) ;
4142
42- const createPeerConnection = useCallback ( ( clientId : string ) : RTCPeerConnection => {
43- const pc = new RTCPeerConnection ( RTC_CONFIG ) ;
43+ const createPeerConnection = useCallback ( async ( clientId : string ) : Promise < RTCPeerConnection > => {
44+ // Fetch ICE servers if not already cached
45+ if ( ! iceServersRef . current ) {
46+ console . log ( 'Fetching TURN server credentials...' ) ;
47+ iceServersRef . current = await fetchIceServers ( ) ;
48+ console . log ( 'ICE servers fetched:' , iceServersRef . current ) ;
49+ }
50+
51+ const pc = new RTCPeerConnection ( { iceServers : iceServersRef . current } ) ;
4452
4553 // Add local stream tracks
4654 // If we're screen sharing, use the screen track, otherwise use camera
@@ -171,7 +179,7 @@ export const useWebRTC = (options?: UseWebRTCOptions) => {
171179 return null ;
172180 }
173181
174- const pc = createPeerConnection ( clientId ) ;
182+ const pc = await createPeerConnection ( clientId ) ;
175183
176184 // Double-check that tracks were added
177185 if ( pc . getSenders ( ) . length === 0 ) {
@@ -219,7 +227,7 @@ export const useWebRTC = (options?: UseWebRTCOptions) => {
219227 let pc = peerConnectionsRef . current . get ( clientId ) ;
220228 if ( ! pc ) {
221229 console . log ( 'Creating new peer connection for offer from:' , clientId ) ;
222- pc = createPeerConnection ( clientId ) ;
230+ pc = await createPeerConnection ( clientId ) ;
223231
224232 if ( ! pc ) {
225233 console . error ( 'Failed to create peer connection for:' , clientId ) ;
0 commit comments