File size: 1,349 Bytes
8b1e853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const API_URL = 'http://localhost:8080';

export const establishPeerConnection = async (token: string): Promise<{ pc: RTCPeerConnection, dc: RTCDataChannel }> => {
  const pc = new RTCPeerConnection();
  
  const dc = pc.createDataChannel('chat');
  dc.onopen = () => console.log('Data channel open');
  dc.onmessage = (event) => console.log('Received message:', event.data);

  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);

  const response = await fetch(`${API_URL}/webrtc/offer`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      sdp: pc.localDescription?.sdp,
      type: pc.localDescription?.type,
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to establish WebRTC connection');
  }

  const data = await response.json();
  const remoteDesc = new RTCSessionDescription(data);
  await pc.setRemoteDescription(remoteDesc);

  pc.onicecandidate = async (event) => {
    if (event.candidate) {
      await fetch(`${API_URL}/webrtc/ice-candidate`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(event.candidate),
      });
    }
  };

  return { pc, dc };
};