Removing log trace
[libreadventure.git] / front / src / WebRtc / SimplePeer.ts
1 import {ConnexionInterface} from "../Connexion";
2 import {MediaManager} from "./MediaManager";
3 let Peer = require('simple-peer');
4
5 class UserSimplePear{
6 userId: string;
7 name?: string;
8 initiator?: boolean;
9 }
10 export class SimplePeerInterface {}
11 export class SimplePeer implements SimplePeerInterface{
12 private Connexion: ConnexionInterface;
13 private WebRtcRoomId: string;
14 private Users: Array<UserSimplePear> = new Array<UserSimplePear>();
15
16 private MediaManager: MediaManager;
17
18 private PeerConnexionArray: Map<string, any> = new Map<string, any>();
19
20 constructor(Connexion: ConnexionInterface, WebRtcRoomId: string = "test-webrtc") {
21 this.Connexion = Connexion;
22 this.WebRtcRoomId = WebRtcRoomId;
23 this.MediaManager = new MediaManager((stream : MediaStream) => {
24 this.updatedLocalStream();
25 });
26 this.initialise();
27 }
28
29 /**
30 * permit to listen when user could start visio
31 */
32 private initialise() {
33
34 //receive signal by gemer
35 this.Connexion.receiveWebrtcSignal((message: string) => {
36 this.receiveWebrtcSignal(message);
37 });
38
39 this.MediaManager.activeVisio();
40 this.MediaManager.getCamera().then(() => {
41
42 //receive message start
43 this.Connexion.receiveWebrtcStart((message: string) => {
44 this.receiveWebrtcStart(message);
45 });
46
47 }).catch((err) => {
48 console.error("err", err);
49 });
50
51 //receive signal by gemer
52 this.Connexion.disconnectMessage((message: string) => {
53 let data = JSON.parse(message);
54 this.closeConnexion(data.userId);
55 });
56 }
57
58 /**
59 *
60 * @param message
61 */
62 private receiveWebrtcStart(message: string) {
63 let data = JSON.parse(message);
64 this.WebRtcRoomId = data.roomId;
65 this.Users = data.clients;
66
67 //start connexion
68 this.startWebRtc();
69 }
70
71 /**
72 * server has two person connected, start the meet
73 */
74 private startWebRtc() {
75 this.Users.forEach((user: UserSimplePear) => {
76 //if it's not an initiator, peer connexion will be created when gamer will receive offer signal
77 if(!user.initiator){
78 return;
79 }
80 this.createPeerConnexion(user);
81 });
82 }
83
84 /**
85 * create peer connexion to bind users
86 */
87 private createPeerConnexion(user : UserSimplePear) {
88 if(this.PeerConnexionArray.has(user.userId)) {
89 return;
90 }
91
92 let name = user.name;
93 if(!name){
94 let userSearch = this.Users.find((userSearch: UserSimplePear) => userSearch.userId === user.userId);
95 if(userSearch) {
96 name = userSearch.name;
97 }
98 }
99 this.MediaManager.removeActiveVideo(user.userId);
100 this.MediaManager.addActiveVideo(user.userId, name);
101
102 let peer : any = new Peer({
103 initiator: user.initiator ? user.initiator : false,
104 reconnectTimer: 10000,
105 config: {
106 iceServers: [
107 {
108 urls: 'stun:stun.l.google.com:19302'
109 },
110 {
111 urls: 'turn:numb.viagenie.ca',
112 username: 'g.parant@thecodingmachine.com',
113 credential: 'itcugcOHxle9Acqi$'
114 },
115 ]
116 },
117 });
118 this.PeerConnexionArray.set(user.userId, peer);
119
120 //start listen signal for the peer connexion
121 this.PeerConnexionArray.get(user.userId).on('signal', (data: any) => {
122 this.sendWebrtcSignal(data, user.userId);
123 });
124
125 this.PeerConnexionArray.get(user.userId).on('stream', (stream: MediaStream) => {
126 let videoActive = false;
127 let microphoneActive = false;
128 stream.getTracks().forEach((track : MediaStreamTrack) => {
129 if(track.kind === "audio"){
130 microphoneActive = true;
131 }
132 if(track.kind === "video"){
133 videoActive = true;
134 }
135 });
136 if(microphoneActive){
137 this.MediaManager.enabledMicrophoneByUserId(user.userId);
138 }else{
139 this.MediaManager.disabledMicrophoneByUserId(user.userId);
140 }
141
142 if(videoActive){
143 this.MediaManager.enabledVideoByUserId(user.userId);
144 }else{
145 this.MediaManager.disabledVideoByUserId(user.userId);
146 }
147 this.stream(user.userId, stream);
148 });
149
150 this.PeerConnexionArray.get(user.userId).on('track', (track: MediaStreamTrack, stream: MediaStream) => {
151 this.stream(user.userId, stream);
152 });
153
154 this.PeerConnexionArray.get(user.userId).on('close', () => {
155 this.closeConnexion(user.userId);
156 });
157
158 this.PeerConnexionArray.get(user.userId).on('error', (err: any) => {
159 console.error(`error => ${user.userId} => ${err.code}`, err);
160 });
161
162 this.PeerConnexionArray.get(user.userId).on('connect', () => {
163 console.info(`connect => ${user.userId}`);
164 });
165
166 this.addMedia(user.userId);
167 }
168
169 private closeConnexion(userId : string) {
170 try {
171 this.MediaManager.removeActiveVideo(userId);
172 if (!this.PeerConnexionArray.get(userId)) {
173 return;
174 }
175 // @ts-ignore
176 this.PeerConnexionArray.get(userId).destroy();
177 this.PeerConnexionArray.delete(userId)
178 } catch (err) {
179 console.error("closeConnexion", err)
180 }
181 }
182
183 /**
184 *
185 * @param userId
186 * @param data
187 */
188 private sendWebrtcSignal(data: any, userId : string) {
189 try {
190 this.Connexion.sendWebrtcSignal(data, this.WebRtcRoomId, null, userId);
191 }catch (e) {
192 console.error(`sendWebrtcSignal => ${userId}`, e);
193 }
194 }
195
196 /**
197 *
198 * @param message
199 */
200 private receiveWebrtcSignal(message: string) {
201 let data = JSON.parse(message);
202 try {
203 //if offer type, create peer connexion
204 if(data.signal.type === "offer"){
205 this.createPeerConnexion(data);
206 }
207 this.PeerConnexionArray.get(data.userId).signal(data.signal);
208 } catch (e) {
209 console.error(`receiveWebrtcSignal => ${data.userId}`, e);
210 }
211 }
212
213 /**
214 *
215 * @param userId
216 * @param stream
217 */
218 private stream(userId : any, stream: MediaStream) {
219 this.MediaManager.addStreamRemoteVideo(userId, stream);
220 }
221
222 /**
223 *
224 * @param userId
225 */
226 private addMedia (userId : any = null) {
227 try {
228 let transceiver : any = null;
229 if(!this.MediaManager.localStream){
230 return;
231 }
232 this.MediaManager.localStream.getTracks().forEach(
233 transceiver = (track: MediaStreamTrack) => this.PeerConnexionArray.get(userId).addTrack(track, this.MediaManager.localStream)
234 )
235 }catch (e) {
236 console.error(`addMedia => addMedia => ${userId}`, e);
237 }
238 }
239
240 updatedLocalStream(){
241 this.Users.forEach((user: UserSimplePear) => {
242 this.addMedia(user.userId);
243 })
244 }
245 }