aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/webcam/DashWebRTCVideo.tsx
blob: f93d4a6626e4bfb4813f132b6d6ca12a8e77adf3 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { observer } from "mobx-react";
import React = require("react");
import { CollectionFreeFormDocumentViewProps } from "../nodes/CollectionFreeFormDocumentView";
import { FieldViewProps, FieldView } from "../nodes/FieldView";
import { observable, action } from "mobx";
import { DocumentDecorations, CloseCall } from "../DocumentDecorations";
import { InkingControl } from "../InkingControl";
import "../../views/nodes/WebBox.scss";
import "./DashWebRTCVideo.scss";
import adapter from 'webrtc-adapter';
import { DocServer } from "../../DocServer";
import { DocumentView } from "../nodes/DocumentView";
import { Utils } from "../../../Utils";
import { MessageStore } from "../../../server/Message";
import { initialize, hangup } from "./WebCamLogic";

const mediaStreamConstraints = {
    video: true,
};

const offerOptions = {
    offerToReceiveVideo: 1,
};

/**
 * This models the component that will be rendered, that can be used as a doc that will reflect the video cams.
 */
@observer
export class DashWebRTCVideo extends React.Component<CollectionFreeFormDocumentViewProps & FieldViewProps> {
    @observable private localVideoEl: HTMLVideoElement | undefined;
    @observable private peerVideoEl: HTMLVideoElement | undefined;
    private roomText: HTMLInputElement | undefined;
    // private roomOfCam: string = "";
    // private isChannelReady = false;
    // private isInitiator = false;
    // private isStarted = false;
    @observable remoteVideoAdded: boolean = false;
    // localStream: MediaStream | undefined;
    // private pc: any;
    // remoteStream: MediaStream | undefined;
    // private turnReady: boolean | undefined;
    // //localVideo: HTMLVideoElement | undefined;
    // //remoteVideo: HTMLVideoElement | undefined;
    // curRoom: string = "";

    // private pcConfig = {
    //     'iceServers': [{
    //         'urls': 'stun:stun.l.google.com:19302'
    //     }]
    // };

    // // Set up audio and video regardless of what devices are present.
    // private sdpConstraints = {
    //     offerToReceiveAudio: true,
    //     offerToReceiveVideo: true
    // };

    componentDidMount() {
        DocumentDecorations.Instance.addCloseCall(this.closeConnection);
        // setTimeout(() => initialize(), 10000);
        // let self = this;
        // window.onbeforeunload = function () {
        //     self.sendMessage('bye');
        // };
    }

    closeConnection: CloseCall = () => {
        hangup();
    }

    @action
    changeUILook = () => {
        this.remoteVideoAdded = true;
    }

    // componentWillUnmount() {
    // }


    // init(room: string) {

    //     this.curRoom = room;
    //     let self = this;

    //     if (room !== '') {
    //         DocServer._socket.emit('create or join', room);
    //         console.log('Attempted to create or  join room', room);

    //     }

    //     DocServer._socket.on('created', function (room: string) {
    //         console.log('Created room ' + room);
    //         self.isInitiator = true;
    //     });

    //     DocServer._socket.on('full', function (room: string) {
    //         console.log('Room ' + room + ' is full');
    //     });

    //     DocServer._socket.on('join', function (room: string) {
    //         console.log('Another peer made a request to join room ' + room);
    //         console.log('This peer is the initiator of room ' + room + '!');
    //         self.isChannelReady = true;
    //     });


    //     DocServer._socket.on('joined', function (room: string) {
    //         console.log('joined: ' + room);
    //         self.isChannelReady = true;
    //     });


    //     DocServer._socket.on('log', function (array: any) {
    //         console.log.apply(console, array);
    //     });

    //     // This client receives a message
    //     DocServer._socket.on('message', async function (message: any) {
    //         console.log('Client received message:', message);
    //         if (message.message === 'got user media') {
    //             self.maybeStart();
    //         } else if (message.message.type === 'offer') {
    //             if (!self.isInitiator && !self.isStarted) {
    //                 self.maybeStart();
    //             }
    //             await self.pc.setRemoteDescription(new RTCSessionDescription(message.message));
    //             self.doAnswer();
    //         } else if (message.message.type === 'answer' && self.isStarted) {
    //             await self.pc.setRemoteDescription(new RTCSessionDescription(message.message));
    //         } else if (message.message.type === 'candidate' && self.isStarted) {
    //             let candidate = new RTCIceCandidate({
    //                 sdpMLineIndex: message.message.label,
    //                 candidate: message.message.candidate
    //             });
    //             self.pc.addIceCandidate(candidate);
    //         } else if (message.message === 'bye' && self.isStarted) {
    //             self.handleRemoteHangup();
    //         }
    //     });

    //     navigator.mediaDevices.getUserMedia({
    //         audio: true,
    //         video: true
    //     })
    //         .then(this.gotStream)
    //         .catch(function (e) {
    //             alert('getUserMedia() error: ' + e.name);
    //         });

    //     //Trying this one out!!!
    //     console.log('Getting user media with constraints', this.constraints);

    //     if (location.hostname !== 'localhost') {
    //         this.requestTurn(
    //             'https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913'
    //         );
    //     }


    // }


    // private sendMessage = (message: any) => {
    //     console.log('Client sending message: ', message);
    //     Utils.Emit(DocServer._socket, MessageStore.NotifyRoommates, { message: message, room: this.curRoom });
    //     //DocServer._socket.emit('message', message);
    // }



    // private gotStream = (stream: any) => {
    //     console.log('Adding local stream.');
    //     this.localStream = stream;
    //     this.localVideoEl!.srcObject = stream;
    //     this.sendMessage('got user media');
    //     if (this.isInitiator) {
    //         this.maybeStart();
    //     }
    // }

    // constraints = {
    //     video: true,
    //     audio: true
    // };





    // private maybeStart = () => {
    //     console.log('>>>>>>> maybeStart() ', this.isStarted, this.localStream, this.isChannelReady);
    //     if (!this.isStarted && typeof this.localStream !== 'undefined' && this.isChannelReady) {
    //         console.log('>>>>>> creating peer connection');
    //         this.createPeerConnection();
    //         this.pc.addStream(this.localStream);
    //         this.isStarted = true;
    //         console.log('isInitiator', this.isInitiator);
    //         if (this.isInitiator) {
    //             this.doCall();
    //         }
    //     }
    // }


    // // //this will need to be changed to our version of hangUp
    // // window.onbeforeunload = function () {
    // //     sendMessage('bye');
    // // };

    // private createPeerConnection = () => {
    //     try {
    //         this.pc = new RTCPeerConnection(undefined);
    //         this.pc.onicecandidate = this.handleIceCandidate;
    //         this.pc.onaddstream = this.handleRemoteStreamAdded;
    //         this.pc.onremovestream = this.handleRemoteStreamRemoved;
    //         console.log('Created RTCPeerConnnection');
    //     } catch (e) {
    //         console.log('Failed to create PeerConnection, exception: ' + e.message);
    //         alert('Cannot create RTCPeerConnection object.');
    //         return;
    //     }
    // }

    // private handleIceCandidate = (event: any) => {
    //     console.log('icecandidate event: ', event);
    //     if (event.candidate) {
    //         this.sendMessage({
    //             type: 'candidate',
    //             label: event.candidate.sdpMLineIndex,
    //             id: event.candidate.sdpMid,
    //             candidate: event.candidate.candidate
    //         });
    //     } else {
    //         console.log('End of candidates.');
    //     }
    // }

    // private handleCreateOfferError = (event: any) => {
    //     console.log('createOffer() error: ', event);
    // }

    // private doCall = () => {
    //     console.log('Sending offer to peer');
    //     this.pc.createOffer(this.setLocalAndSendMessage, this.handleCreateOfferError);
    // }

    // private doAnswer = () => {
    //     console.log('Sending answer to peer.');
    //     this.pc.createAnswer().then(
    //         this.setLocalAndSendMessage,
    //         this.onCreateSessionDescriptionError
    //     );
    // }

    // private setLocalAndSendMessage = (sessionDescription: any) => {
    //     this.pc.setLocalDescription(sessionDescription);
    //     console.log('setLocalAndSendMessage sending message', sessionDescription);
    //     this.sendMessage(sessionDescription);
    // }

    // private onCreateSessionDescriptionError = (error: any) => {
    //     console.log('Failed to create session description: ' + error.toString());
    // }


    // private requestTurn = (turnURL: any) => {
    //     var turnExists = false;
    //     let self = this;
    //     for (var i in this.pcConfig.iceServers) {
    //         if (this.pcConfig.iceServers[i].urls.substr(0, 5) === 'turn:') {
    //             turnExists = true;
    //             this.turnReady = true;
    //             break;
    //         }
    //     }
    //     if (!turnExists) {
    //         console.log('Getting TURN server from ', turnURL);
    //         // No TURN server. Get one from computeengineondemand.appspot.com:
    //         var xhr = new XMLHttpRequest();
    //         xhr.onreadystatechange = function () {
    //             if (xhr.readyState === 4 && xhr.status === 200) {
    //                 var turnServer = JSON.parse(xhr.responseText);
    //                 console.log('Got TURN server: ', turnServer);
    //                 self.pcConfig.iceServers.push({
    //                     'urls': 'turn:' + turnServer.username + '@' + turnServer.turn,
    //                     //'credential': turnServer.password
    //                 });
    //                 self.turnReady = true;
    //             }
    //         };
    //         xhr.open('GET', turnURL, true);
    //         xhr.send();
    //     }
    // }
    // @action
    // private handleRemoteStreamAdded = (event: MediaStreamEvent) => {
    //     console.log('Remote stream added.');
    //     this.remoteStream = event.stream!;
    //     this.peerVideoEl!.srcObject = this.remoteStream;
    //     this.remoteVideoAdded = true;
    // }

    // private handleRemoteStreamRemoved = (event: MediaStreamEvent) => {
    //     console.log('Remote stream removed. Event: ', event);
    // }

    // private hangup = () => {
    //     console.log('Hanging up.');
    //     if (this.pc) {
    //         stop();
    //         this.sendMessage('bye');
    //     }

    //     if (this.localStream) {
    //         this.localStream.getTracks().forEach(track => track.stop());
    //     }

    // }

    // private handleRemoteHangup = () => {
    //     console.log('Session terminated.');
    //     this.stop();
    //     this.isInitiator = false;

    //     if (this.localStream) {
    //         this.localStream.getTracks().forEach(track => track.stop());
    //     }


    // }

    // private stop = () => {
    //     this.isStarted = false;
    //     this.pc.close();
    //     this.pc = null;
    // }






    /**
      * Function that submits the title entered by user on enter press.
      */
    private onEnterKeyDown = (e: React.KeyboardEvent) => {
        if (e.keyCode === 13) {
            let submittedTitle = this.roomText!.value;
            this.roomText!.value = "";
            this.roomText!.blur();
            initialize(submittedTitle, this.changeUILook);
        }
    }


    public static LayoutString(fieldKey: string) { return FieldView.LayoutString(DashWebRTCVideo, fieldKey); }

    _ignore = 0;
    onPreWheel = (e: React.WheelEvent) => {
        this._ignore = e.timeStamp;
    }
    onPrePointer = (e: React.PointerEvent) => {
        this._ignore = e.timeStamp;
    }
    onPostPointer = (e: React.PointerEvent) => {
        if (this._ignore !== e.timeStamp) {
            e.stopPropagation();
        }
    }
    onPostWheel = (e: React.WheelEvent) => {
        if (this._ignore !== e.timeStamp) {
            e.stopPropagation();
        }
    }

    render() {
        let content =
            <div className="webcam-cont" style={{ width: "100%", height: "100%" }} onWheel={this.onPostWheel} onPointerDown={this.onPostPointer} onPointerMove={this.onPostPointer} onPointerUp={this.onPostPointer}>
                <div className="webcam-header">DashWebRTC</div>
                <input id="roomName" type="text" placeholder="Enter room name" ref={(e) => this.roomText = e!} onKeyDown={this.onEnterKeyDown} />
                <video id="localVideo" className={"RTCVideo" + (this.remoteVideoAdded ? " side" : " main")} autoPlay playsInline ref={(e) => {
                    this.localVideoEl = e!;
                }}></video>
                <video id="remoteVideo" className="RTCVideo main" autoPlay playsInline ref={(e) => {
                    this.peerVideoEl = e!;
                }}></video>

            </div >;

        let frozen = !this.props.isSelected() || DocumentDecorations.Instance.Interacting;
        let classname = "webBox-cont" + (this.props.isSelected() && !InkingControl.Instance.selectedTool && !DocumentDecorations.Instance.Interacting ? "-interactive" : "");


        return (
            <>
                <div className={classname}  >
                    {content}
                </div>
                {!frozen ? (null) : <div className="webBox-overlay" onWheel={this.onPreWheel} onPointerDown={this.onPrePointer} onPointerMove={this.onPrePointer} onPointerUp={this.onPrePointer} />}
            </>);
    }


}