summaryrefslogtreecommitdiffstats
path: root/webapp/client/webrtc_session.jsx
blob: df60a1053210c2d7cc16ff54dced7e1b7e17f045 (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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import adapter from 'webrtc-adapter';
import WebrtcClient from './webrtc_client.jsx';
const transationLength = 12;

export default class WebrtcSession {
    static randomString(len) {
        const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let randomString = '';
        for (let i = 0; i < len; i++) {
            const randomPoz = Math.floor(Math.random() * charSet.length);
            randomString += charSet.substring(randomPoz, randomPoz + 1);
        }
        return randomString;
    }

    static getLocalMedia(constraints, element, callback) {
        const media = constraints || {audio: true, video: true};
        navigator.mediaDevices.getUserMedia(media).
        then((stream) => {
            if (element) {
                element.srcObject = stream;
            }

            if (callback && typeof callback === 'function') {
                callback(null, stream);
            }
        }).
        catch((error) => {
            callback(error);
        });
    }

    static stopMediaStream(stream) {
        const tracks = stream.getTracks();
        tracks.forEach((track) => {
            track.stop();
        });
    }

    constructor(opts) {
        // super();
        const options = opts || {};
        this.getServer = this.getServer.bind(this);
        this.isConnected = this.isConnected.bind(this);
        this.getSessionId = this.getSessionId.bind(this);
        this.handleEvent = this.handleEvent.bind(this);
        this.keepAlive = this.keepAlive.bind(this);
        this.createSession = this.createSession.bind(this);
        this.attach = this.attach.bind(this);
        this.sendMessage = this.sendMessage.bind(this);
        this.sendTrickleCandidate = this.sendTrickleCandidate.bind(this);
        this.sendData = this.sendData.bind(this);
        this.sendDtmf = this.sendDtmf.bind(this);
        this.destroy = this.destroy.bind(this);
        this.destroyHandle = this.destroyHandle.bind(this);
        this.streamsDone = this.streamsDone.bind(this);
        this.prepareWebrtc = this.prepareWebrtc.bind(this);
        this.prepareWebrtcPeer = this.prepareWebrtcPeer.bind(this);
        this.createOffer = this.createOffer.bind(this);
        this.createAnswer = this.createAnswer.bind(this);
        this.sendSDP = this.sendSDP.bind(this);
        this.getVolume = this.getVolume.bind(this);
        this.isMuted = this.isMuted.bind(this);
        this.mute = this.mute.bind(this);
        this.getBitrate = this.getBitrate.bind(this);
        this.webrtcError = this.webrtcError.bind(this);
        this.cleanupWebrtc = this.cleanupWebrtc.bind(this);
        this.isAudioSendEnabled = this.isAudioSendEnabled.bind(this);
        this.isAudioRecvEnabled = this.isAudioRecvEnabled.bind(this);
        this.isVideoSendEnabled = this.isVideoSendEnabled.bind(this);
        this.isVideoRecvEnabled = this.isVideoRecvEnabled.bind(this);
        this.isDataEnabled = this.isDataEnabled.bind(this);
        this.isTrickleEnabled = this.isTrickleEnabled.bind(this);
        this.unbindWebSocket = this.unbindWebSocket.bind(this);

        this.websockets = false;
        this.ws = null;
        this.wsHandlers = {};
        this.wsKeepaliveTimeoutId = null;
        this.servers = null;
        this.server = null;
        this.serversIndex = 0;
        this.connected = false;
        this.sessionId = null;
        this.pluginHandles = {};
        this.retries = 0;
        this.transactions = {};

        this.client = new WebrtcClient();
        this.client.init({debug: options.debug});

        this.gatewayCallbacks = options || {};
        this.gatewayCallbacks.success = (typeof options.success == 'function') ? options.success : this.client.noop;
        this.gatewayCallbacks.error = (typeof options.error == 'function') ? options.error : this.client.noop;
        this.gatewayCallbacks.destroyed = (typeof options.destroyed == 'function') ? options.destroyed : this.client.noop;

        if (!this.client.initDone) {
            this.gatewayCallbacks.error('webrtc_client.not_initialize', 'Library not initialized');
            return {};
        }

        if (!this.client.isWebrtcSupported()) {
            this.gatewayCallbacks.error('webrtc_client.browser.not_supported', 'WebRTC not supported by this browser');
            return {};
        }

        this.client.log('Library initialized: ' + this.client.initDone);

        if (!options.server) {
            this.gatewayCallbacks.error('webrtc_client.invalid_gateway', 'Invalid gateway url');
            return {};
        }

        if (Array.isArray(options.server)) {
            this.client.log('Multiple servers provided (' + options.server.length + '), will use the first that works');
            for (let i = 0; i < options.server; i++) {
                const server = options.server[i];
                if (server.indexOf('ws') !== 0) {
                    this.gatewayCallbacks.error('webrtc_client.must_be_websocket', 'every server provided must be a websocket');
                    return {};
                }
            }
            this.servers = options.server;
            this.client.debug(this.servers);
        } else if (options.server.indexOf('ws') === 0) {
            this.websockets = true;
            this.servers = [options.server];
            this.client.log('Using WebSockets to contact Janus: ' + options.server);
        } else {
            this.gatewayCallbacks.error('webrtc_client.invalid_websocket', 'This library must connect to a websocket');
            return {};
        }

        this.iceServers = options.iceServers;
        if (!this.iceServers || this.iceServers.length === 0) {
            this.iceServers = [{url: 'stun:stun.l.google.com:19302'}];
        }

        // Optional max events
        this.maxev = null;
        if (options.max_poll_events) {
            this.maxev = options.max_poll_events;
        }
        if (this.maxev < 1) {
            this.maxev = 1;
        }

        // Token to use (only if the token based authentication mechanism is enabled)
        this.token = null;
        if (options.token) {
            this.token = options.token;
        }

        // API secret to use (only if the shared API secret is enabled)
        this.apisecret = null;
        if (options.apisecret) {
            this.apisecret = options.apisecret;
        }

        // Whether we should destroy this session when onbeforeunload is called
        this.destroyOnUnload = options.destroyOnUnload !== false;
        this.createSession();

        return this;
    }

    getServer() {
        return this.server;
    }

    isConnected() {
        return this.connected;
    }

    getSessionId() {
        return this.sessionId;
    }

    handleEvent(json) {
        this.retries = 0;
        this.client.debug('Got event on session ' + this.sessionId);
        this.client.debug(json);
        const transaction = json.transaction;
        const sender = json.sender;
        const plugindata = json.plugindata;
        const jsep = json.jsep;
        switch (json.janus) {
        case 'keepalive':
            // Nothing happened
            break;
        case 'ack':
        case 'success':
            // Success or just an ack, we can probably ignore
            if (transaction) {
                const reportSuccess = this.transactions[transaction];
                if (reportSuccess) {
                    reportSuccess(json);
                }
                Reflect.deleteProperty(this.transactions, transaction);
            }
            break;
        case 'webrtcup':
            // The PeerConnection with the gateway is up! Notify this
            if (sender) {
                const pluginHandle = this.pluginHandles[sender];
                if (pluginHandle) {
                    pluginHandle.webrtcState(true);
                } else {
                    this.client.warn('This handle is not attached to this session');
                }
            } else {
                this.client.warn('Missing sender...');
            }
            break;
        case 'hangup':
            // A plugin asked the core to hangup a PeerConnection on one of our handles
            if (sender) {
                const pluginHandle = this.pluginHandles[sender];
                if (pluginHandle) {
                    pluginHandle.webrtcState(false);
                    pluginHandle.hangup();
                } else {
                    this.client.warn('This handle is not attached to this session');
                }
            } else {
                this.client.warn('Missing sender...');
            }
            break;
        case 'detached':
            // A plugin asked the core to detach one of our handles
            if (sender) {
                const pluginHandle = this.pluginHandles[sender];
                if (pluginHandle) {
                    pluginHandle.ondetached();
                    pluginHandle.detach();
                } else {
                    this.client.warn('This handle is not attached to this session');
                }
            } else {
                this.client.warn('Missing sender...');
            }
            break;
        case 'media':
            // Media started/stopped flowing
            if (sender) {
                const pluginHandle = this.pluginHandles[sender];
                if (pluginHandle) {
                    pluginHandle.mediaState(json.type, json.receiving);
                } else {
                    this.client.warn('This handle is not attached to this session');
                }
            } else {
                this.client.warn('Missing sender...');
            }
            break;
        case 'error':
            // Oops, something wrong happened
            this.client.error('Ooops: ' + json.error.code + ' ' + json.error.reason);
            if (transaction) {
                const reportSuccess = this.transactions[transaction];
                if (reportSuccess) {
                    reportSuccess(json);
                }
                Reflect.deleteProperty(this.transactions, transaction);
            }
            break;
        case 'event':
            if (sender) {
                if (plugindata) {
                    this.client.debug(`  -- Event is coming from ${sender} ( ${plugindata.plugin} )`);
                    const data = plugindata.data;
                    this.client.debug(data);
                    const pluginHandle = this.pluginHandles[sender];
                    if (pluginHandle) {
                        pluginHandle.mediaState(json.type, json.receiving);
                        if (jsep) {
                            this.client.debug('Handling SDP as well...');
                            this.client.debug(jsep);
                        }
                        const callback = pluginHandle.onmessage;
                        if (callback) {
                            this.client.debug('Notifying application...');

                            // Send to callback specified when attaching plugin handle
                            callback(data, jsep);
                        } else {
                            // Send to generic callback (?)
                            this.client.debug('No provided notification callback');
                        }
                    } else {
                        this.client.warn('This handle is not attached to this session');
                    }
                } else {
                    this.client.warn('Missing plugindata...');
                }
            } else {
                this.client.warn('Missing sender...');
            }
            break;
        default:
            this.client.warn(`Unknown message "${json.janus}"`);
            break;
        }
    }

    keepAlive() {
        if (this.server === null || !this.websockets || !this.connected) {
            return;
        }
        this.wsKeepaliveTimeoutId = setTimeout(this.keepAlive, 30000);

        const request = {
            janus: 'keepalive',
            session_id: this.sessionId,
            transaction: WebrtcSession.randomString(transationLength)
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }

        this.ws.send(JSON.stringify(request));
    }

    createSession() {
        const transaction = WebrtcSession.randomString(transationLength);
        const request = {
            janus: 'create',
            transaction
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }

        if (this.server === null && Array.isArray(this.servers)) {
            // We still need to find a working server from the list we were given
            this.server = this.servers[this.serversIndex];
            if (this.server.indexOf('ws') === 0) {
                this.websockets = true;
                this.client.log('Server #' + (this.serversIndex + 1) + ': trying WebSockets to contact Janus (' + this.server + ')');
            }
        }

        if (this.websockets) {
            this.ws = new WebSocket(this.server, 'janus-protocol');
            this.wsHandlers = {
                error: () => {
                    this.client.error('Error connecting to the Janus WebSockets server... ' + this.server);
                    if (Array.isArray(this.servers)) {
                        this.serversIndex++;
                        if (this.serversIndex === this.servers.length) {
                            // We tried all the servers the user gave us and they all failed
                            this.gatewayCallbacks.error('webrtc_client.cannot_connect_servers', 'Error connecting to any of the provided Janus servers: Is the gateway down?');
                            return;
                        }

                        // Let's try the next server
                        this.server = null;
                        setTimeout(() => {
                            this.createSession();
                        }, 200);
                        return;
                    }
                    this.gatewayCallbacks.error('webrtc_client.cannot_connect_server', 'Error connecting to the Janus WebSockets server: Is the gateway down?');
                },

                open: () => {
                    // We need to be notified about the success
                    this.transactions[transaction] = (json) => {
                        this.client.debug(json);
                        if (json.janus !== 'success') {
                            this.client.error('Ooops: ' + json.error.code + ' ' + json.error.reason);	// FIXME
                            this.gatewayCallbacks.error(json.error.reason);
                            return;
                        }
                        this.wsKeepaliveTimeoutId = setTimeout(this.keepAlive, 30000);
                        this.connected = true;
                        this.sessionId = json.data.id;
                        this.client.log('Created session: ' + this.sessionId);
                        this.client.sessions[this.sessionId] = this;
                        this.gatewayCallbacks.success();
                    };
                    this.ws.send(JSON.stringify(request));
                },

                message: (event) => {
                    this.handleEvent(JSON.parse(event.data));
                },

                close: () => {
                    if (!this.connected) {
                        return;
                    }
                    this.connected = false;

                    // FIXME What if this is called when the page is closed?
                    this.gatewayCallbacks.error('Lost connection to the gateway (is it down?)');
                }
            };

            for (var eventName in this.wsHandlers) {
                if (this.wsHandlers.hasOwnProperty(eventName)) {
                    this.ws.addEventListener(eventName, this.wsHandlers[eventName]);
                }
            }
        }
    }

    attach(cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;
        callbacks.consentDialog = (typeof cbs.consentDialog == 'function') ? cbs.consentDialog : this.client.noop;
        callbacks.mediaState = (typeof cbs.mediaState == 'function') ? cbs.mediaState : this.client.noop;
        callbacks.webrtcState = (typeof cbs.webrtcState == 'function') ? cbs.webrtcState : this.client.noop;
        callbacks.onmessage = (typeof cbs.onmessage == 'function') ? cbs.onmessage : this.client.noop;
        callbacks.onlocalstream = (typeof cbs.onlocalstream == 'function') ? cbs.onlocalstream : this.client.noop;
        callbacks.onremotestream = (typeof cbs.onremotestream == 'function') ? cbs.onremotestream : this.client.noop;
        callbacks.ondata = (typeof cbs.ondata == 'function') ? cbs.ondata : this.client.noop;
        callbacks.ondataopen = (typeof cbs.ondataopen == 'function') ? cbs.ondataopen : this.client.noop;
        callbacks.oncleanup = (typeof cbs.oncleanup == 'function') ? cbs.oncleanup : this.client.noop;
        callbacks.ondetached = (typeof cbs.ondetached == 'function') ? cbs.ondetached : this.client.noop;

        if (!this.connected) {
            this.client.warn('Is the gateway down? (connected=false)');
            callbacks.error('Is the gateway down? (connected=false)');
            return;
        }

        const plugin = callbacks.plugin;
        if (!plugin) {
            this.client.error('Invalid plugin');
            callbacks.error('Invalid plugin');
            return;
        }

        const transaction = WebrtcSession.randomString(transationLength);
        const request = {
            janus: 'attach',
            plugin,
            transaction
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }

        if (this.websockets) {
            this.transactions[transaction] = (json) => {
                this.client.debug(json);

                if (json.janus !== 'success') {
                    const error = `Ooops: ${json.error.code} ${json.error.reason}`;
                    this.client.error(error);
                    callbacks.error(error);
                    return;
                }

                const handleId = json.data.id;

                this.client.log('Created handle: ' + handleId);
                const pluginHandle = {
                    session: this,
                    plugin,
                    id: handleId,
                    webrtcStuff: {
                        started: false,
                        myStream: null,
                        streamExternal: false,
                        remoteStream: null,
                        mySdp: null,
                        pc: null,
                        dataChannel: null,
                        dtmfSender: null,
                        trickle: true,
                        iceDone: false,
                        sdpSent: false,
                        volume: {
                            value: null,
                            timer: null
                        },
                        bitrate: {
                            value: null,
                            bsnow: null,
                            bsbefore: null,
                            tsnow: null,
                            tsbefore: null,
                            timer: null
                        }
                    },
                    getId: () => {
                        return handleId;
                    },
                    getPlugin: () => {
                        return plugin;
                    },
                    getVolume: () => {
                        return this.getVolume(handleId);
                    },
                    isAudioMuted: () => {
                        return this.isMuted(handleId, false);
                    },
                    muteAudio: () => {
                        return this.mute(handleId, false, true);
                    },
                    unmuteAudio: () => {
                        return this.mute(handleId, false, false);
                    },
                    isVideoMuted: () => {
                        return this.isMuted(handleId, true);
                    },
                    muteVideo: () => {
                        return this.mute(handleId, true, true);
                    },
                    unmuteVideo: () => {
                        return this.mute(handleId, true, false);
                    },
                    getBitrate: () => {
                        return this.getBitrate(handleId);
                    },
                    send: (cb) => {
                        this.sendMessage(handleId, cb);
                    },
                    data: (cb) => {
                        this.sendData(handleId, cb);
                    },
                    dtmf: (cb) => {
                        this.sendDtmf(handleId, cb);
                    },
                    consentDialog: callbacks.consentDialog,
                    mediaState: callbacks.mediaState,
                    webrtcState: callbacks.webrtcState,
                    onmessage: callbacks.onmessage,
                    createOffer: (cb) => {
                        this.prepareWebrtc(handleId, cb);
                    },
                    createAnswer: (cb) => {
                        this.prepareWebrtc(handleId, cb);
                    },
                    handleRemoteJsep: (cb) => {
                        this.prepareWebrtcPeer(handleId, cb);
                    },
                    onlocalstream: callbacks.onlocalstream,
                    onremotestream: callbacks.onremotestream,
                    ondata: callbacks.ondata,
                    ondataopen: callbacks.ondataopen,
                    oncleanup: callbacks.oncleanup,
                    ondetached: callbacks.ondetached,
                    hangup: (sendRequest) => {
                        this.cleanupWebrtc(handleId, sendRequest === true);
                    },
                    detach: (cb) => {
                        this.destroyHandle(handleId, cb);
                    }
                };
                this.pluginHandles[handleId] = pluginHandle;
                callbacks.success(pluginHandle);
            };
            request.session_id = this.sessionId;
            this.ws.send(JSON.stringify(request));
        }
    }

    sendMessage(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;

        if (!this.connected) {
            const error = 'Is the gateway down? (connected=false)';
            this.client.warn(error);
            callbacks.error(error);
            return;
        }

        const message = callbacks.message;
        const jsep = callbacks.jsep;
        const transaction = WebrtcSession.randomString(transationLength);
        const request = {
            janus: 'message',
            body: message,
            transaction
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }

        if (jsep) {
            request.jsep = jsep;
        }

        this.client.debug('Sending message to plugin (handle=' + handleId + '):');
        this.client.debug(request);

        if (this.websockets) {
            request.session_id = this.sessionId;
            request.handle_id = handleId;
            this.transactions[transaction] = (json) => {
                this.client.debug('Message sent!');
                this.client.debug(json);

                if (json.janus === 'success') {
                    // We got a success, must have been a synchronous transaction
                    const plugindata = json.plugindata;
                    if (!plugindata) {
                        this.client.warn('Request succeeded, but missing plugindata...');
                        callbacks.success();
                        return;
                    }

                    this.client.log('Synchronous transaction successful (' + plugindata.plugin + ')');
                    const data = plugindata.data;
                    this.client.debug(data);
                    callbacks.success(data);
                    return;
                } else if (json.janus !== 'ack') {
                    // Not a success and not an ack, must be an error
                    if (json.error) {
                        this.client.error('Ooops: ' + json.error.code + ' ' + json.error.reason);
                        callbacks.error(json.error.code + ' ' + json.error.reason);
                    } else {
                        this.client.error('Unknown error');
                        callbacks.error('Unknown error');
                    }
                    return;
                }

                // If we got here, the plugin decided to handle the request asynchronously
                callbacks.success();
            };
            this.ws.send(JSON.stringify(request));
        }
    }

    sendTrickleCandidate(handleId, candidate) {
        if (!this.connected) {
            this.client.warn('Is the gateway down? (connected=false)');
            return;
        }
        var request = {
            janus: 'trickle',
            candidate,
            transaction: WebrtcSession.randomString(transationLength)
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }
        this.client.debug('Sending trickle candidate (handle=' + handleId + '):');
        this.client.debug(request);

        if (this.websockets) {
            request.session_id = this.sessionId;
            request.handle_id = handleId;
            this.ws.send(JSON.stringify(request));
        }
    }

    sendData(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        const text = callbacks.text;
        if (!text) {
            this.client.warn('Invalid text');
            callbacks.error('Invalid text');
            return;
        }
        this.client.log('Sending string on data channel: ' + text);
        config.dataChannel.send(text);
        callbacks.success();
    }

    sendDtmf(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;

        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        if (!config.dtmfSender) {
            // Create the DTMF sender, if possible
            if (config.myStream) {
                const tracks = config.myStream.getAudioTracks();
                if (tracks && tracks.length > 0) {
                    const localAudioTrack = tracks[0];
                    config.dtmfSender = config.pc.createDTMFSender(localAudioTrack);
                    this.client.log('Created DTMF Sender');
                    config.dtmfSender.ontonechange = (tone) => {
                        this.client.debug('Sent DTMF tone: ' + tone.tone);
                    };
                }
            }
            if (!config.dtmfSender) {
                this.client.warn('Invalid DTMF configuration');
                callbacks.error('Invalid DTMF configuration');
                return;
            }
        }

        const dtmf = callbacks.dtmf;
        if (!dtmf) {
            this.client.warn('Invalid DTMF parameters');
            callbacks.error('Invalid DTMF parameters');
            return;
        }

        const tones = dtmf.tones;
        if (!tones) {
            this.client.warn('Invalid DTMF string');
            callbacks.error('Invalid DTMF string');
            return;
        }

        let duration = dtmf.duration;
        if (!duration) {
            duration = 500;	// We choose 500ms as the default duration for a tone
        }

        let gap = dtmf.gap;
        if (!gap) {
            gap = 50;	// We choose 50ms as the default gap between tones
        }

        this.client.debug('Sending DTMF string ' + tones + ' (duration ' + duration + 'ms, gap ' + gap + 'ms');
        config.dtmfSender.insertDTMF(tones, duration, gap);
    }

    destroy(sync) {
        const syncRequest = (sync === true);
        this.client.log('Destroying session ' + this.sessionId);

        if (!this.connected) {
            this.client.warn('Is the gateway down? (connected=false)');
            return;
        }

        if (!this.sessionId) {
            this.client.warn('No session to destroy');
            this.gatewayCallbacks.destroyed();
            return;
        }

        Reflect.deleteProperty(this.client.sessions, this.sessionId);

        // Destroy all handles first
        for (const ph in this.pluginHandles) {
            if (this.pluginHandles.hasOwnProperty(ph)) {
                const phv = this.pluginHandles[ph];
                this.client.log('Destroying handle ' + phv.id + ' (' + phv.plugin + ')');
                this.destroyHandle(phv.id, null, syncRequest);
            }
        }

        // Ok, go on
        var request = {janus: 'destroy', transaction: WebrtcSession.randomString(transationLength)};

        if (this.token) {
            request.token = this.token;
        }
        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }
        if (this.websockets) {
            request.session_id = this.sessionId;

            let onUnbindMessage = null;
            let onUnbindError = null;
            onUnbindMessage = (event) => {
                var data = JSON.parse(event.data);
                if (data.session_id === request.session_id && data.transaction === request.transaction) {
                    this.unbindWebSocket(onUnbindMessage, onUnbindError);
                    this.gatewayCallbacks.destroyed();
                }
            };
            onUnbindError = () => {
                this.unbindWebSocket(onUnbindMessage, onUnbindError);
                this.gatewayCallbacks.destroyed();
            };

            this.ws.addEventListener('message', onUnbindMessage);
            this.ws.addEventListener('error', onUnbindError);

            this.ws.send(JSON.stringify(request));
        }
    }

    disconnect() {
        this.connected = false;
        this.ws.close();
    }

    destroyHandle(handleId, cbs, sync) {
        const syncRequest = (sync === true);
        this.client.log('Destroying handle ' + handleId + ' (sync=' + syncRequest + ')');
        const callbacks = cbs || {};
        callbacks.success = (typeof callbacks.success == 'function') ? callbacks.success : this.client.noop;
        callbacks.error = (typeof callbacks.error == 'function') ? callbacks.error : this.client.noop;
        this.cleanupWebrtc(handleId);
        if (!this.connected) {
            this.client.warn('Is the gateway down? (connected=false)');
            return;
        }
        const request = {
            janus: 'detach',
            transaction: WebrtcSession.randomString(transationLength)
        };

        if (this.token) {
            request.token = this.token;
        }

        if (this.apisecret) {
            request.apisecret = this.apisecret;
        }

        if (this.websockets) {
            request.session_id = this.sessionId;
            request.handle_id = handleId;
            this.ws.send(JSON.stringify(request));

            Reflect.deleteProperty(this.pluginHandles, handleId);

            callbacks.success();
        }
    }

    streamsDone(handleId, jsep, media, callbacks, stream) {
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        this.client.debug('streamsDone:', stream);
        config.myStream = stream;

        const pcConfig = {iceServers: this.iceServers};
        const pcConstraints = {
            optional: [{DtlsSrtpKeyAgreement: true}]
        };

        this.client.log('Creating PeerConnection');
        this.client.debug(pcConstraints);
        config.pc = new window.RTCPeerConnection(pcConfig, pcConstraints);
        this.client.debug(config.pc);
        if (config.pc.getStats) {	// FIXME
            config.volume.value = 0;
            config.bitrate.value = '0 kbits/sec';
        }
        this.client.log('Preparing local SDP and gathering candidates (trickle=' + config.trickle + ')');

        config.pc.onicecandidate = (event) => {
            if (!event.candidate || (adapter.browserDetails.browser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0)) {
                this.client.log('End of candidates.');
                config.iceDone = true;
                if (config.trickle === true) {
                    // Notify end of candidates
                    this.sendTrickleCandidate(handleId, {completed: true});
                } else {
                    // No trickle, time to send the complete SDP (including all candidates)
                    this.sendSDP(handleId, callbacks);
                }
            } else {
                // JSON.stringify doesn't work on some WebRTC objects anymore
                // See https://code.google.com/p/chromium/issues/detail?id=467366
                const candidate = {
                    candidate: event.candidate.candidate,
                    sdpMid: event.candidate.sdpMid,
                    sdpMLineIndex: event.candidate.sdpMLineIndex
                };

                if (config.trickle === true) {
                    // Send candidate
                    this.sendTrickleCandidate(handleId, candidate);
                }
            }
        };

        if (stream) {
            this.client.log('Adding local stream');
            config.pc.addStream(stream);
            pluginHandle.onlocalstream(stream);
        }

        config.pc.onaddstream = (remoteStream) => {
            this.client.log('Handling Remote Stream');
            this.client.debug(remoteStream);
            config.remoteStream = remoteStream;
            pluginHandle.onremotestream(remoteStream.stream);
        };

        // Any data channel to create?
        if (this.isDataEnabled(media)) {
            this.client.log('Creating data channel');
            const onDataChannelMessage = (event) => {
                this.client.log('Received message on data channel: ' + event.data);
                pluginHandle.ondata(event.data);	// FIXME
            };

            const onDataChannelStateChange = () => {
                const dcState = config.dataChannel ? config.dataChannel.readyState : 'null';
                this.client.log('State change on data channel: ' + dcState);
                if (dcState === 'open') {
                    pluginHandle.ondataopen();	// FIXME
                }
            };

            const onDataChannelError = (error) => {
                this.client.error('Got error on data channel:', error);

                // TODO
            };

            // Until we implement the proxying of open requests within the this.client core, we open a channel ourselves whatever the case
            config.dataChannel = config.pc.createDataChannel('this.clientDataChannel', {ordered: false});	// FIXME Add options (ordered, maxRetransmits, etc.)
            config.dataChannel.onmessage = onDataChannelMessage;
            config.dataChannel.onopen = onDataChannelStateChange;
            config.dataChannel.onclose = onDataChannelStateChange;
            config.dataChannel.onerror = onDataChannelError;
        }

        // Create offer/answer now DO I WANT THIS??
        if (jsep) {
            config.pc.setRemoteDescription(
                new RTCSessionDescription(jsep),
                () => {
                    this.client.log('Remote description accepted!');
                    this.createAnswer(handleId, media, callbacks);
                }, callbacks.error);
        } else {
            this.createOffer(handleId, media, callbacks);
        }
    }

    prepareWebrtc(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.webrtcError;
        const jsep = callbacks.jsep;
        const media = callbacks.media;
        const pluginHandle = this.pluginHandles[handleId];

        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;

        // Are we updating a session?
        if (config.pc) {
            this.client.log('Updating existing media session');

            // Create offer/answer now
            if (jsep) {
                config.pc.setRemoteDescription(
                    new window.RTCSessionDescription(jsep),
                    () => {
                        this.client.log('Remote description accepted!');
                        this.createAnswer(handleId, media, callbacks);
                    }, callbacks.error);
            } else {
                this.createOffer(handleId, media, callbacks);
            }
            return;
        }

        // Was a MediaStream object passed, or do we need to take care of that?
        if (callbacks.stream) {
            const stream = callbacks.stream;
            this.client.log('MediaStream provided by the application');
            this.client.debug(stream);

            // Skip the getUserMedia part
            config.streamExternal = true;
            this.streamsDone(handleId, jsep, media, callbacks, stream);
            return;
        }

        config.trickle = this.isTrickleEnabled(callbacks.trickle);
        if (this.isAudioSendEnabled(media) || this.isVideoSendEnabled(media)) {
            let constraints = {mandatory: {}, optional: []};
            pluginHandle.consentDialog(true);

            let audioSupport = this.isAudioSendEnabled(media);
            if (audioSupport === true && media) {
                if (typeof media.audio === 'object') {
                    audioSupport = media.audio;
                }
            }

            let videoSupport = this.isVideoSendEnabled(media);
            if (videoSupport === true && media) {
                if (media.video && media.video !== 'screen' && media.video !== 'window') {
                    let width = 0;
                    let height = 0;
                    let maxHeight = 0;

                    if (media.video === 'lowres') {
                        // Small resolution, 4:3
                        height = 240;
                        maxHeight = 240;
                        width = 320;
                    } else if (media.video === 'lowres-16:9') {
                        // Small resolution, 16:9
                        height = 180;
                        maxHeight = 180;
                        width = 320;
                    } else if (media.video === 'hires' || media.video === 'hires-16:9') {
                        // High resolution is only 16:9
                        height = 720;
                        maxHeight = 720;
                        width = 1280;
                        if (navigator.mozGetUserMedia) {
                            const firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
                            if (firefoxVer < 38) {
                                // Unless this is and old Firefox, which doesn't support it
                                this.client.warn(media.video + ' unsupported, falling back to stdres (old Firefox)');
                                height = 480;
                                maxHeight = 480;
                                width = 640;
                            }
                        }
                    } else if (media.video === 'stdres') {
                        // Normal resolution, 4:3
                        height = 480;
                        maxHeight = 480;
                        width = 640;
                    } else if (media.video === 'stdres-16:9') {
                        // Normal resolution, 16:9
                        height = 360;
                        maxHeight = 360;
                        width = 640;
                    } else {
                        this.client.log('Default video setting (' + media.video + ') is stdres 4:3');
                        height = 480;
                        maxHeight = 480;
                        width = 640;
                    }

                    this.client.log('Adding media constraint ' + media.video);

                    if (navigator.mozGetUserMedia) {
                        const firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
                        if (firefoxVer < 38) {
                            videoSupport = {
                                require: ['height', 'width'],
                                height: {max: maxHeight, min: height},
                                width: {max: width, min: width}
                            };
                        } else {
                            // http://stackoverflow.com/questions/28282385/webrtc-firefox-constraints/28911694#28911694
                            // https://github.com/meetecho/janus-gateway/pull/246
                            videoSupport = {
                                height: {ideal: height},
                                width: {ideal: width}
                            };
                        }
                    } else {
                        videoSupport = {
                            mandatory: {
                                maxHeight,
                                minHeight: height,
                                maxWidth: width,
                                minWidth: width
                            },
                            optional: []
                        };
                    }

                    if (typeof media.video === 'object') {
                        videoSupport = media.video;
                    }

                    this.client.debug(videoSupport);
                } else if (media.video === 'screen' || media.video === 'window') {
                    // Not a webcam, but screen capture
                    if (window.location.protocol !== 'https:') {
                        // Screen sharing mandates HTTPS
                        this.client.warn('Screen sharing only works on HTTPS, try the https:// version of this page');
                        pluginHandle.consentDialog(false);
                        callbacks.error('Screen sharing only works on HTTPS, try the https:// version of this page');
                        return;
                    }

                    // We're going to try and use the extension for Chrome 34+, the old approach
                    // for older versions of Chrome, or the experimental support in Firefox 33+
                    const cache = {};
                    const self = this;

                    function callbackUserMedia(error, stream) {
                        pluginHandle.consentDialog(false);
                        if (error) {
                            callbacks.error({code: error.code, name: error.name, message: error.message});
                        } else {
                            self.streamsDone(handleId, jsep, media, callbacks, stream);
                        }
                    }

                    function getScreenMedia(constraint, gsmCallback) {
                        this.client.log('Adding media constraint (screen capture)');
                        this.client.debug(constraint);
                        navigator.mediaDevices.getUserMedia(constraint).
                        then((stream) => {
                            gsmCallback(null, stream);
                        }).
                        catch((error) => {
                            pluginHandle.consentDialog(false);
                            gsmCallback(error);
                        });
                    }

                    if (window.navigator.userAgent.match('Chrome')) {
                        const chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
                        let maxver = 33;

                        if (window.navigator.userAgent.match('Linux')) {
                            maxver = 35;	// 'known' crash in chrome 34 and 35 on linux
                        }

                        if (chromever >= 26 && chromever <= maxver) {
                            // Chrome 26->33 requires some awkward chrome://flags manipulation
                            constraints = {
                                video: {
                                    mandatory: {
                                        googLeakyBucket: true,
                                        maxWidth: window.screen.width,
                                        maxHeight: window.screen.height,
                                        maxFrameRate: 3,
                                        chromeMediaSource: 'screen'
                                    }
                                },
                                audio: this.isAudioSendEnabled(media)
                            };
                            getScreenMedia(constraints, callbackUserMedia);
                        } else {
                            // Chrome 34+ requires an extension
                            var pending = window.setTimeout(
                                () => {
                                    const error = new Error('NavigatorUserMediaError');
                                    error.name = 'The required Chrome extension is not installed: click <a href="#">here</a> to install it. (NOTE: this will need you to refresh the page)';
                                    pluginHandle.consentDialog(false);
                                    return callbacks.error(error);
                                }, 1000);
                            cache[pending] = [callbackUserMedia, null];
                            window.postMessage({
                                type: 'janusGetScreen',
                                id: pending
                            }, '*');
                        }
                    } else if (window.navigator.userAgent.match('Firefox')) {
                        const ffver = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
                        if (ffver >= 33) {
                            // Firefox 33+ has experimental support for screen sharing
                            constraints = {
                                video: {
                                    mozMediaSource: media.video,
                                    mediaSource: media.video
                                },
                                audio: this.isAudioSendEnabled(media)
                            };
                            getScreenMedia(constraints, (err, stream) => {
                                callbackUserMedia(err, stream);

                                // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1045810
                                if (!err) {
                                    let lastTime = stream.currentTime;
                                    const polly = window.setInterval(() => {
                                        if (!stream) {
                                            window.clearInterval(polly);
                                        }

                                        if (stream.currentTime === lastTime) {
                                            window.clearInterval(polly);
                                            if (stream.onended) {
                                                stream.onended();
                                            }
                                        }

                                        lastTime = stream.currentTime;
                                    }, 500);
                                }
                            });
                        } else {
                            const error = new Error('NavigatorUserMediaError');
                            error.name = 'Your version of Firefox does not support screen sharing, please install Firefox 33 (or more recent versions)';
                            pluginHandle.consentDialog(false);
                            callbacks.error(error);
                            return;
                        }
                    }

                    // Wait for events from the Chrome Extension
                    window.addEventListener('message', (event) => {
                        if (event.origin !== window.location.origin) {
                            return;
                        }
                        if (event.data.type === 'mattermostGotScreen' && cache[event.data.id]) {
                            const data = cache[event.data.id];
                            const callback = data[0];

                            Reflect.deleteProperty(cache, event.data.id);

                            if (event.data.sourceId === '') {
                                // user canceled
                                const error = new Error('NavigatorUserMediaError');
                                error.name = 'You cancelled the request for permission, giving up...';
                                pluginHandle.consentDialog(false);
                                callbacks.error(error);
                            } else {
                                constraints = {
                                    audio: this.isAudioSendEnabled(media),
                                    video: {
                                        mandatory: {
                                            chromeMediaSource: 'desktop',
                                            maxWidth: window.screen.width,
                                            maxHeight: window.screen.height,
                                            maxFrameRate: 3
                                        },
                                        optional: [
                                            {googLeakyBucket: true},
                                            {googTemporalLayeredScreencast: true}
                                        ]
                                    }
                                };
                                constraints.video.mandatory.chromeMediaSourceId = event.data.sourceId;
                                getScreenMedia(constraints, callback);
                            }
                        } else if (event.data.type === 'mattermostGetScreenPending') {
                            window.clearTimeout(event.data.id);
                        }
                    });
                    return;
                }
            }

            // If we got here, we're not screensharing
            if (!media || media.video !== 'screen') {
                // Check whether all media sources are actually available or not
                navigator.mediaDevices.enumerateDevices().then((devices) => {
                    const audioExist = devices.some((device) => {
                        return device.kind === 'audioinput';
                    });

                    const videoExist = devices.some((device) => {
                        return device.kind === 'videoinput';
                    });

                    // Check whether a missing device is really a problem
                    const audioSend = this.isAudioSendEnabled(media);
                    const videoSend = this.isVideoSendEnabled(media);

                    if (audioSend || videoSend) {
                        // We need to send either audio or video
                        const haveAudioDevice = audioSend ? audioExist : false;
                        const haveVideoDevice = videoSend ? videoExist : false;

                        if (!haveAudioDevice && !haveVideoDevice) {
                            // FIXME Should we really give up, or just assume recvonly for both?
                            pluginHandle.consentDialog(false);
                            callbacks.error('No capture device found');
                            return false;
                        }
                    }

                    navigator.mediaDevices.getUserMedia({
                        audio: audioExist ? audioSupport : false,
                        video: videoExist ? videoSupport : false
                    }).
                    then((stream) => {
                        pluginHandle.consentDialog(false);
                        this.streamsDone(handleId, jsep, media, callbacks, stream);
                    }).
                    catch((error) => {
                        pluginHandle.consentDialog(false);
                        callbacks.error({
                            code: error.code,
                            name: error.name,
                            message: error.message
                        });
                    });

                    return true;
                }).
                catch((error) => {
                    pluginHandle.consentDialog(false);
                    callbacks.error('enumerateDevices error', error);
                });
            }
        } else {
            // No need to do a getUserMedia, create offer/answer right away
            this.streamsDone(handleId, jsep, media, callbacks);
        }
    }

    prepareWebrtcPeer(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.webrtcError;

        const jsep = callbacks.jsep;
        const pluginHandle = this.pluginHandles[handleId];

        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;

        if (jsep) {
            if (config.pc === null) {
                this.client.warn('Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep');
                callbacks.error('No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep');
                return;
            }
            config.pc.setRemoteDescription(
                new window.RTCSessionDescription(jsep),
                () => {
                    this.client.log('Remote description accepted!');
                    callbacks.success();
                }, callbacks.error);
        } else {
            callbacks.error('Invalid JSEP');
        }
    }

    createOffer(handleId, media, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;

        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        this.client.log('Creating offer (iceDone=' + config.iceDone + ')');

        // https://code.google.com/p/webrtc/issues/detail?id=3508
        let mediaConstraints = null;
        const browser = adapter.browserDetails.browser;
        if (browser === 'firefox' || browser === 'edge') {
            mediaConstraints = {
                offerToReceiveAudio: this.isAudioRecvEnabled(media),
                offerToReceiveVideo: this.isVideoRecvEnabled(media)
            };
        } else {
            mediaConstraints = {
                mandatory: {
                    OfferToReceiveAudio: this.isAudioRecvEnabled(media),
                    OfferToReceiveVideo: this.isVideoRecvEnabled(media)
                }
            };
        }

        this.client.debug(mediaConstraints);
        config.pc.createOffer(
            (offer) => {
                this.client.debug(offer);

                if (!config.mySdp) {
                    this.client.log('Setting local description');
                    config.mySdp = offer.sdp;
                    config.pc.setLocalDescription(offer);
                }

                if (!config.iceDone && !config.trickle) {
                    // Don't do anything until we have all candidates
                    this.client.log('Waiting for all candidates...');
                    return;
                }

                if (config.sdpSent) {
                    this.client.log('Offer already sent, not sending it again');
                    return;
                }

                this.client.log('Offer ready');
                this.client.debug(callbacks);
                config.sdpSent = true;

                // JSON.stringify doesn't work on some WebRTC objects anymore
                // See https://code.google.com/p/chromium/issues/detail?id=467366
                const jsep = {
                    type: offer.type,
                    sdp: offer.sdp
                };
                callbacks.success(jsep);
            }, callbacks.error, mediaConstraints);
    }

    createAnswer(handleId, media, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;

        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            callbacks.error('Invalid handle');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        this.client.log('Creating answer (iceDone=' + config.iceDone + ')');

        let mediaConstraints = null;
        const browser = adapter.browserDetails.browser;
        if (browser === 'firefox' || browser === 'edge') {
            mediaConstraints = {
                offerToReceiveAudio: this.isAudioRecvEnabled(media),
                offerToReceiveVideo: this.isVideoRecvEnabled(media)
            };
        } else {
            mediaConstraints = {
                mandatory: {
                    OfferToReceiveAudio: this.isAudioRecvEnabled(media),
                    OfferToReceiveVideo: this.isVideoRecvEnabled(media)
                }
            };
        }
        this.client.debug(mediaConstraints);
        config.pc.createAnswer(
            (answer) => {
                this.client.debug(answer);
                if (!config.mySdp) {
                    this.client.log('Setting local description');
                    config.mySdp = answer.sdp;
                    config.pc.setLocalDescription(answer);
                }
                if (!config.iceDone && !config.trickle) {
                    // Don't do anything until we have all candidates
                    this.client.log('Waiting for all candidates...');
                    return;
                }
                if (config.sdpSent) {	// FIXME badly
                    this.client.log('Answer already sent, not sending it again');
                    return;
                }
                config.sdpSent = true;

                // JSON.stringify doesn't work on some WebRTC objects anymore
                // See https://code.google.com/p/chromium/issues/detail?id=467366
                const jsep = {
                    type: answer.type,
                    sdp: answer.sdp
                };
                callbacks.success(jsep);
            }, callbacks.error, mediaConstraints);
    }

    sendSDP(handleId, cbs) {
        const callbacks = cbs || {};
        callbacks.success = (typeof cbs.success == 'function') ? cbs.success : this.client.noop;
        callbacks.error = (typeof cbs.error == 'function') ? cbs.error : this.client.noop;

        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle, not sending anything');
            return;
        }

        const config = pluginHandle.webrtcStuff;
        this.client.log('Sending offer/answer SDP...');
        if (!config.mySdp) {
            this.client.warn('Local SDP instance is invalid, not sending anything...');
            return;
        }

        config.mySdp = {
            type: config.pc.localDescription.type,
            sdp: config.pc.localDescription.sdp
        };

        if (config.sdpSent) {
            this.client.log('Offer/Answer SDP already sent, not sending it again');
            return;
        }

        if (config.trickle === false) {
            config.mySdp.trickle = false;
        }
        this.client.debug(callbacks);
        config.sdpSent = true;
        callbacks.success(config.mySdp);
    }

    getVolume(handleId) {
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            return 0;
        }

        const config = pluginHandle.webrtcStuff;
        const browser = adapter.browserDetails.browser;

        // Start getting the volume, if getStats is supported
        if (config.pc.getStats && browser === 'chrome') {	// FIXME
            if (!config.remoteStream) {
                this.client.warn('Remote stream unavailable');
                return 0;
            }

            // http://webrtc.googlecode.com/svn/trunk/samples/js/demos/html/constraints-and-stats.html
            if (!config.volume.timer) {
                this.client.log('Starting volume monitor');
                config.volume.timer = setInterval(() => {
                    config.pc.getStats((stats) => {
                        const results = stats.result();
                        for (let i = 0; i < results.length; i++) {
                            const res = results[i];
                            if (res.type === 'ssrc' && res.stat('audioOutputLevel')) {
                                config.volume.value = res.stat('audioOutputLevel');
                            }
                        }
                    });
                }, 200);
                return 0;	// We don't have a volume to return yet
            }
            return config.volume.value;
        }

        this.client.log('Getting the remote volume unsupported by browser');
        return 0;
    }

    isMuted(handleId, video) {
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            return true;
        }

        const config = pluginHandle.webrtcStuff;

        if (!config.pc) {
            this.client.warn('Invalid PeerConnection');
            return true;
        }

        if (!config.myStream) {
            this.client.warn('Invalid local MediaStream');
            return true;
        }

        if (video) {
            // Check video track
            if (!config.myStream.getVideoTracks() || config.myStream.getVideoTracks().length === 0) {
                this.client.warn('No video track');
                return true;
            }
            return !config.myStream.getVideoTracks()[0].enabled;
        }

        // Check audio track
        if (!config.myStream.getAudioTracks() || config.myStream.getAudioTracks().length === 0) {
            this.client.warn('No audio track');
            return true;
        }
        return !config.myStream.getAudioTracks()[0].enabled;
    }

    mute(handleId, video, mute) {
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            return false;
        }

        const config = pluginHandle.webrtcStuff;
        if (!config.pc) {
            this.client.warn('Invalid PeerConnection');
            return false;
        }

        if (!config.myStream) {
            this.client.warn('Invalid local MediaStream');
            return false;
        }

        if (video) {
            // Mute/unmute video track
            if (!config.myStream.getVideoTracks() || config.myStream.getVideoTracks().length === 0) {
                this.client.warn('No video track');
                return false;
            }
            config.myStream.getVideoTracks()[0].enabled = mute;
            return true;
        }

        // Mute/unmute audio track
        if (!config.myStream.getAudioTracks() || config.myStream.getAudioTracks().length === 0) {
            this.client.warn('No audio track');
            return false;
        }
        config.myStream.getAudioTracks()[0].enabled = mute;
        return true;
    }

    getBitrate(handleId) {
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle || !pluginHandle.webrtcStuff) {
            this.client.warn('Invalid handle');
            return 'Invalid handle';
        }

        const config = pluginHandle.webrtcStuff;
        if (!config.pc) {
            return 'Invalid PeerConnection';
        }

        // Start getting the bitrate, if getStats is supported
        const browser = adapter.browserDetails.browser;
        if (config.pc.getStats && browser === 'chrome') {
            // Do it the Chrome way
            if (!config.remoteStream) {
                this.client.warn('Remote stream unavailable');
                return 'Remote stream unavailable';
            }

            // http://webrtc.googlecode.com/svn/trunk/samples/js/demos/html/constraints-and-stats.html
            if (!config.bitrate.timer) {
                this.client.log('Starting bitrate timer (Chrome)');
                config.bitrate.timer = setInterval(() => {
                    config.pc.getStats((stats) => {
                        const results = stats.result();
                        for (let i = 0; i < results.length; i++) {
                            const res = results[i];
                            if (res.type === 'ssrc' && res.stat('googFrameHeightReceived')) {
                                config.bitrate.bsnow = res.stat('bytesReceived');
                                config.bitrate.tsnow = res.timestamp;
                                if (config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
                                    // Skip this round
                                    config.bitrate.bsbefore = config.bitrate.bsnow;
                                    config.bitrate.tsbefore = config.bitrate.tsnow;
                                } else {
                                    // Calculate bitrate
                                    var bitRate = Math.round(((config.bitrate.bsnow - config.bitrate.bsbefore) * 8) / (config.bitrate.tsnow - config.bitrate.tsbefore));
                                    config.bitrate.value = bitRate + ' kbits/sec';

                                    //~ this.client.log('Estimated bitrate is ' + config.bitrate.value);
                                    config.bitrate.bsbefore = config.bitrate.bsnow;
                                    config.bitrate.tsbefore = config.bitrate.tsnow;
                                }
                            }
                        }
                    });
                }, 1000);
                return '0 kbits/sec';	// We don't have a bitrate value yet
            }
            return config.bitrate.value;
        } else if (config.pc.getStats && browser === 'firefox') {
            // Do it the Firefox way
            if (!config.remoteStream || !config.remoteStream.stream) {
                this.client.warn('Remote stream unavailable');
                return 'Remote stream unavailable';
            }

            const videoTracks = config.remoteStream.stream.getVideoTracks();
            if (!videoTracks || videoTracks.length < 1) {
                this.client.warn('No video track');
                return 'No video track';
            }

            // https://github.com/muaz-khan/getStats/blob/master/getStats.js
            if (!config.bitrate.timer) {
                this.client.log('Starting bitrate timer (Firefox)');
                config.bitrate.timer = setInterval(() => {
                    // We need a helper callback
                    function cb(res) {
                        if (!res || res.inbound_rtp_video_1 == null || res.inbound_rtp_video_1 == null) {
                            config.bitrate.value = 'Missing inbound_rtp_video_1';
                            return;
                        }

                        config.bitrate.bsnow = res.inbound_rtp_video_1.bytesReceived;
                        config.bitrate.tsnow = res.inbound_rtp_video_1.timestamp;

                        if (config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
                            // Skip this round
                            config.bitrate.bsbefore = config.bitrate.bsnow;
                            config.bitrate.tsbefore = config.bitrate.tsnow;
                        } else {
                            // Calculate bitrate
                            var bitRate = Math.round(((config.bitrate.bsnow - config.bitrate.bsbefore) * 8) / (config.bitrate.tsnow - config.bitrate.tsbefore));
                            config.bitrate.value = bitRate + ' kbits/sec';
                            config.bitrate.bsbefore = config.bitrate.bsnow;
                            config.bitrate.tsbefore = config.bitrate.tsnow;
                        }
                    }

                    // Actually get the stats
                    config.pc.getStats(videoTracks[0], (stats) => {
                        cb(stats);
                    }, cb);
                }, 1000);
                return '0 kbits/sec';	// We don't have a bitrate value yet
            }
            return config.bitrate.value;
        }

        this.client.warn('Getting the video bitrate unsupported by browser');
        return 'Feature unsupported by browser';
    }

    webrtcError(error) {
        this.client.error('WebRTC error:', error);
    }

    cleanupWebrtc(handleId, hangupRequest) {
        this.client.log('Cleaning WebRTC stuff');
        const pluginHandle = this.pluginHandles[handleId];
        if (!pluginHandle) {
            // Nothing to clean
            return;
        }

        const config = pluginHandle.webrtcStuff;
        if (config) {
            if (hangupRequest === true) {
                // Send a hangup request (we don't really care about the response)
                const request = {
                    janus: 'hangup',
                    transaction: WebrtcSession.randomString(transationLength)
                };

                if (this.token) {
                    request.token = this.token;
                }

                if (this.apisecret) {
                    request.apisecret = this.apisecret;
                }

                this.client.debug('Sending hangup request (handle=' + handleId + '):');
                this.client.debug(request);
                if (this.websockets) {
                    request.session_id = this.sessionId;
                    request.handle_id = handleId;
                    this.ws.send(JSON.stringify(request));
                }
            }

            // Cleanup stack
            config.remoteStream = null;
            if (config.volume.timer) {
                clearInterval(config.volume.timer);
            }

            config.volume.value = null;
            if (config.bitrate.timer) {
                clearInterval(config.bitrate.timer);
            }

            config.bitrate.timer = null;
            config.bitrate.bsnow = null;
            config.bitrate.bsbefore = null;
            config.bitrate.tsnow = null;
            config.bitrate.tsbefore = null;
            config.bitrate.value = null;

            try {
                // Try a MediaStream.stop() first
                if (!config.streamExternal && config.myStream) {
                    this.client.log('Stopping local stream');
                    config.myStream.stop();
                }
            } catch (e) {
                // Do nothing if this fails
            }

            try {
                // Try a MediaStreamTrack.stop() for each track as well
                if (!config.streamExternal && config.myStream) {
                    this.client.log('Stopping local stream tracks');
                    WebrtcSession.stopMediaStream(config.myStream);
                }
            } catch (e) {
                // Do nothing if this fails
            }

            config.streamExternal = false;
            config.myStream = null;

            // Close PeerConnection
            try {
                config.pc.close();
            } catch (e) {
                // Do nothing
            }
            config.pc = null;
            config.mySdp = null;
            config.iceDone = false;
            config.sdpSent = false;
            config.dataChannel = null;
            config.dtmfSender = null;
        }
        pluginHandle.oncleanup();
    }

    isAudioSendEnabled(media) {
        this.client.debug('isAudioSendEnabled:', media);
        if (!media) {
            return true;	// Default
        }

        if (media.audio === false) {
            return false;	// Generic audio has precedence
        }

        if (!media.audioSend) {
            return true;	// Default
        }

        return (media.audioSend === true);
    }

    isAudioRecvEnabled(media) {
        this.client.debug('isAudioRecvEnabled:', media);
        if (!media) {
            return true;	// Default
        }

        if (media.audio === false) {
            return false;	// Generic audio has precedence
        }

        if (!media.audioRecv) {
            return true;	// Default
        }

        return (media.audioRecv === true);
    }

    isVideoSendEnabled(media) {
        this.client.debug('isVideoSendEnabled:', media);
        const browser = adapter.browserDetails.browser;
        if (browser === 'edge') {
            this.client.warn("Edge doesn't support compatible video yet");
            return false;
        }

        if (!media) {
            return true;	// Default
        }

        if (media.video === false) {
            return false;	// Generic video has precedence
        }

        if (!media.videoSend) {
            return true;	// Default
        }

        return (media.videoSend === true);
    }

    isVideoRecvEnabled(media) {
        this.client.debug('isVideoRecvEnabled:', media);
        const browser = adapter.browserDetails.browser;
        if (browser === 'edge') {
            this.client.warn("Edge doesn't support compatible video yet");
            return false;
        }

        if (!media) {
            return true;	// Default
        }

        if (media.video === false) {
            return false;	// Generic video has precedence
        }

        if (!media.videoRecv) {
            return true;	// Default
        }

        return (media.videoRecv === true);
    }

    isDataEnabled(media) {
        this.client.debug('isDataEnabled:', media);
        const browser = adapter.browserDetails.browser;
        if (browser === 'edge') {
            this.client.warn("Edge doesn't support data channels yet");
            return false;
        }

        if (!media) {
            return false;	// Default
        }

        return (media.data === true);
    }

    isTrickleEnabled(trickle) {
        this.client.debug('isTrickleEnabled:', trickle);
        if (!trickle) {
            return true;	// Default is true
        }

        return (trickle === true);
    }

    unbindWebSocket(onUnbindMessage, onUnbindError) {
        for (var eventName in this.wsHandlers) {
            if (this.wsHandlers.hasOwnProperty(eventName)) {
                this.ws.removeEventListener(eventName, this.wsHandlers[eventName]);
            }
        }
        this.ws.removeEventListener('message', onUnbindMessage);
        this.ws.removeEventListener('error', onUnbindError);
        if (this.wsKeepaliveTimeoutId) {
            clearTimeout(this.wsKeepaliveTimeoutId);
        }
    }
}