answerScript.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (function (){
  2. const urlParams = new URLSearchParams(window.location.search);
  3. const connectionParam = urlParams.get('connection')
  4. console.log(atob(connectionParam));
  5. const decoded = atob(connectionParam);
  6. const bits = decoded.split('xxxxx');
  7. const connection = {description: bits[0], candidate: bits[1]}
  8. console.dir(connection);
  9. createRemoteConnection(connection);
  10. })();
  11. function createRemoteConnection(remoteDescJSON) {
  12. const remoteDesc = {
  13. type: "offer",
  14. sdp: remoteDescJSON.description
  15. }
  16. const remoteCandidate = {
  17. candidate: remoteDescJSON.candidate,
  18. sdpMid: "0", // Media stream ID for audio
  19. sdpMLineIndex: 0 // Something to do with media
  20. }
  21. const remoteConnection = new RTCPeerConnection();
  22. let connectionDescription = '';
  23. remoteConnection.setRemoteDescription(remoteDesc).then((e) => {
  24. console.log(e)
  25. });
  26. remoteConnection.addIceCandidate(remoteCandidate).then(
  27. () => {console.log('yes')}
  28. )
  29. remoteConnection.createAnswer().then((desc) => {
  30. remoteConnection.setLocalDescription(desc);
  31. console.dir(desc);
  32. connectionDescription = desc.sdp;
  33. })
  34. remoteConnection.onicecandidate = e => {
  35. if (e.candidate) {
  36. const candidate = e.candidate.candidate;
  37. const body = connectionDescription;
  38. fetch(
  39. 'http://localhost:8000/state/json',
  40. {
  41. method: 'post',
  42. headers: {'Content-Type': 'text/plain'},
  43. body
  44. }
  45. ).then(response => {
  46. if (response.status !== 200) {
  47. throw new Error('bad status ' + response.status);
  48. }
  49. })
  50. }
  51. }
  52. remoteConnection.onicecandidateerror = err => {
  53. console.log(err)
  54. }
  55. remoteConnection.ondatachannel = (e) => {
  56. console.log('onDataChannel')
  57. const receiveChannel = e.channel;
  58. console.dir(receiveChannel);
  59. receiveChannel.onopen = () => {
  60. console.log('channel open')
  61. receiveChannel.send('testing testing 123');
  62. }
  63. receiveChannel.onmessage = (msg) => {
  64. document.body.append(msg.data);
  65. }
  66. }
  67. }