Advertisement
Chatenium

Untitled

Dec 24th, 2023
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.78 KB | None | 0 0
  1. // CLIENT:
  2. const configuration = {
  3. 'iceServers': [
  4. { 'urls': 'stun:stun.l.google.com:19302' },
  5. { urls: 'turn:192.168.1.71:3478', username: 'username', credential: 'password' }
  6. ]
  7. }
  8.  
  9. var peerConnection = new RTCPeerConnection(configuration);
  10.  
  11. peerConnection.addEventListener('connectionstatechange', event => {
  12. if (peerConnection.connectionState === 'connected') {
  13. console.warn("SUCCESS! PEERS CONNECTED")
  14. }
  15. });
  16.  
  17. this.checkloginservice.socket$.subscribe(
  18. async (message) => {
  19. let action = (message as websocketDef).action
  20. switch (action) {
  21. case "offer":
  22. peerConnection.addEventListener('icecandidate', (event) => {
  23. if (event.candidate) {
  24. console.log(event.candidate)
  25. this.checkloginservice.socket$.next({
  26. Action: 'icecandidate',
  27. Value: JSON.stringify({
  28. for: this.callData.peerdata.userid,
  29. icecandidate: JSON.stringify(event.candidate),
  30. action: "icecandidate"
  31. })
  32. })
  33. }
  34. });
  35. let data = message as incomingCallData
  36. this.incomingCall = {
  37. callerDisplayname: data.displayName,
  38. callerId: data.userid,
  39. callerPfp: data.pfp,
  40. chatid: data.chatid,
  41. }
  42.  
  43. setTimeout(() => {
  44. this.document.querySelector(".ans")?.addEventListener("click", async () => {
  45. peerConnection.setRemoteDescription(new RTCSessionDescription(JSON.parse(data.offer)))
  46. const answer = await peerConnection.createAnswer();
  47. await peerConnection.setLocalDescription(answer);
  48. this.checkloginservice.socket$.next({
  49. Action: "answer",
  50. Value: JSON.stringify({
  51. for: data.userid,
  52. answer: JSON.stringify(answer),
  53. action: "answer"
  54. })
  55. })
  56. })
  57. }, 10);
  58. break;
  59. case "answer":
  60. peerConnection.addEventListener('icecandidate', (event) => {
  61. if (event.candidate) {
  62. console.log(event.candidate)
  63. this.checkloginservice.socket$.next({
  64. Action: 'icecandidate',
  65. Value: JSON.stringify({
  66. for: this.callData.peerdata.userid,
  67. icecandidate: JSON.stringify(event.candidate),
  68. action: "icecandidate"
  69. })
  70. })
  71. }
  72. });
  73. let answerData = message as answerCallData
  74. const remoteDesc = new RTCSessionDescription(JSON.parse(answerData.answer));
  75. await peerConnection.setRemoteDescription(remoteDesc);
  76. break;
  77.  
  78. case "icecandidate":
  79. let icacand = message as iceCandData
  80.  
  81. try {
  82. await peerConnection.addIceCandidate(JSON.parse(icacand.icecandidate));
  83. } catch (e) {
  84. console.error('Error adding received ice candidate', e);
  85. }
  86.  
  87. }
  88. }
  89. )
  90.  
  91. this.msgService.callFriend$.subscribe(async (calldata) => {
  92. if (calldata.friendid != '') {
  93. if (await this.chkMicPerms()) {
  94. let stream = await this.getUserMedia(false)
  95. if (stream == typeof String) {
  96. this.toastService.add({
  97. severity: "error",
  98. summary: this.translateService.instant("callFailed"),
  99. detail: this.translateService.instant(stream)
  100. })
  101. } else {
  102. localStream = stream as MediaStream
  103. this.callData.peerdata.userid = calldata.friendid
  104. this.callData.peerdata.displayName = calldata.friendname;
  105. this.callData.peerdata.pfp = calldata.friendpfp;
  106. this.callData.chatid = calldata.chatid;
  107. const offer = await peerConnection.createOffer({
  108. offerToReceiveAudio: true
  109. });
  110. await peerConnection.setLocalDescription(offer)
  111. this.checkloginservice.socket$.next({
  112. Action: 'offer',
  113. Value: JSON.stringify({
  114. for: calldata.friendid,
  115. offer: JSON.stringify(offer),
  116. username: userData.username,
  117. userid: userData.userid,
  118. displayName: userData.displayName,
  119. pfp: userData.pfp,
  120. chatid: calldata.chatid,
  121. action: "offer"
  122. })
  123. })
  124. }
  125.  
  126. } else {
  127. this.toastService.add({
  128. severity: "error",
  129. summary: this.translateService.instant("callFailed"),
  130. detail: this.translateService.instant("provideMic")
  131. })
  132. }
  133. }
  134. })
  135.  
  136.  
  137. // SERVER
  138. var (
  139. upgrader = websocket.Upgrader{
  140. CheckOrigin: func(r *http.Request) bool {
  141. return true
  142. },
  143. }
  144.  
  145. Rm = &roomManager{
  146. rooms: make(map[string]*Client),
  147. mu: sync.Mutex{},
  148. }
  149. )
  150.  
  151. func (rm *roomManager) Broadcast(message interface{}, userid string) {
  152. rm.mu.Lock()
  153. defer rm.mu.Unlock()
  154.  
  155. for _, userConnection := range rm.rooms {
  156. if userConnection.Connection != nil && userConnection.Userid == userid {
  157. // if err := userConnection.Connection.WriteJSON(message); err != nil {}
  158. userConnection.Connection.WriteJSON(message)
  159. }
  160. }
  161. }
  162.  
  163. func HandleWebSocket(c *gin.Context) {
  164. conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  165. if err != nil {
  166. return
  167. }
  168.  
  169. client := &Client{
  170. Connection: conn,
  171. }
  172.  
  173. for {
  174. _, p, err := conn.ReadMessage()
  175.  
  176. if err != nil {
  177. Rm.removeUser(client.Userid)
  178. return
  179. }
  180.  
  181. var message config.Websocket_DefaultMessage
  182. if err := json.Unmarshal(p, &message); err != nil {
  183. return
  184. }
  185.  
  186. switch message.Action {
  187. case "joinRealtime":
  188.  
  189. Rm.connectUser(conn, message.Value)
  190. client.Userid = message.Value
  191. Rm.Broadcast("Connected to WebSocket /user", message.Value)
  192.  
  193. case "offer":
  194. type offerData struct {
  195. For string `json:"for"`
  196. Offer string `json:"offer"`
  197. Username string `json:"username"`
  198. Userid string `json:"userid"`
  199. DisplayName string `json:"displayName"`
  200. Pfp string `json:"pfp"`
  201. Chatid string `json:"chatid"`
  202. Action string `json:"action"`
  203. }
  204.  
  205. var offer offerData
  206.  
  207. if err := json.Unmarshal([]byte(message.Value), &offer); err != nil {
  208. return
  209. }
  210. Rm.Broadcast(offer, offer.For)
  211.  
  212. case "answer":
  213. type answerData struct {
  214. For string `json:"for"`
  215. Answer string `json:"answer"`
  216. Action string `json:"action"`
  217. }
  218.  
  219. var answer answerData
  220.  
  221. if err := json.Unmarshal([]byte(message.Value), &answer); err != nil {
  222. return
  223. }
  224.  
  225. Rm.Broadcast(answer, answer.For)
  226.  
  227. case "icecandidate":
  228. type iceCandData struct {
  229. For string `json:"for"`
  230. Action string `json:"action"`
  231. Icecandidate string `json:"icecandidate"`
  232. }
  233.  
  234. var iceCand iceCandData
  235.  
  236. if err := json.Unmarshal([]byte(message.Value), &iceCand); err != nil {
  237. return
  238. }
  239. Rm.Broadcast(iceCand, iceCand.For)
  240. }
  241. }
  242. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement