Bläddra i källkod

[eslint] no-var

release-8443
Lyubo Marinov 8 år sedan
förälder
incheckning
5bff0ed543
58 ändrade filer med 756 tillägg och 741 borttagningar
  1. 3
    0
      .eslintignore
  2. 1
    0
      .eslintrc.js
  3. 26
    26
      JitsiConference.js
  4. 27
    27
      JitsiConferenceEventManager.js
  5. 3
    3
      JitsiConnection.js
  6. 4
    4
      JitsiMediaDevices.js
  7. 8
    8
      JitsiMeetJS.js
  8. 1
    1
      JitsiParticipant.js
  9. 1
    1
      JitsiRecorderErrors.js
  10. 4
    2
      JitsiTrackError.js
  11. 19
    19
      doc/example/example.js
  12. 2
    2
      modules/DTMF/JitsiDTMFManager.js
  13. 23
    23
      modules/RTC/DataChannels.js
  14. 10
    10
      modules/RTC/JitsiLocalTrack.js
  15. 11
    11
      modules/RTC/JitsiRemoteTrack.js
  16. 8
    8
      modules/RTC/JitsiTrack.js
  17. 7
    7
      modules/RTC/RTC.js
  18. 27
    31
      modules/RTC/RTCBrowserType.js
  19. 5
    5
      modules/RTC/RTCUIHelper.js
  20. 57
    56
      modules/RTC/RTCUtils.js
  21. 22
    22
      modules/RTC/ScreenObtainer.js
  22. 22
    22
      modules/RTC/TraceablePeerConnection.js
  23. 4
    4
      modules/connectivity/ConnectionQuality.js
  24. 2
    2
      modules/settings/Settings.js
  25. 14
    14
      modules/statistics/CallStats.js
  26. 14
    14
      modules/statistics/LocalStatsCollector.js
  27. 60
    58
      modules/statistics/RTPStatsCollector.js
  28. 12
    12
      modules/statistics/statistics.js
  29. 22
    22
      modules/transcription/audioRecorder.js
  30. 1
    1
      modules/transcription/recordingResult.js
  31. 22
    22
      modules/transcription/transcriber.js
  32. 1
    1
      modules/transcription/transcriberHolder.js
  33. 2
    2
      modules/transcription/transcriptionServices/AbstractTranscriptionService.js
  34. 11
    11
      modules/transcription/transcriptionServices/SphinxTranscriptionService.js
  35. 1
    1
      modules/transcription/word.js
  36. 2
    2
      modules/util/AuthUtil.js
  37. 2
    2
      modules/util/EventEmitterForwarder.js
  38. 6
    6
      modules/util/GlobalOnErrorHandler.js
  39. 7
    7
      modules/util/RandomUtil.js
  40. 9
    9
      modules/util/ScriptUtil.js
  41. 4
    4
      modules/util/UsernameGenerator.js
  42. 5
    5
      modules/version/ComponentsVersions.js
  43. 55
    51
      modules/xmpp/ChatRoom.js
  44. 67
    67
      modules/xmpp/SDP.js
  45. 19
    19
      modules/xmpp/SDPDiffer.js
  46. 55
    50
      modules/xmpp/SDPUtil.js
  47. 34
    34
      modules/xmpp/moderator.js
  48. 20
    19
      modules/xmpp/recording.js
  49. 1
    1
      modules/xmpp/xmpp.js
  50. 1
    1
      service/RTC/CameraFacingMode.js
  51. 1
    1
      service/RTC/RTCEvents.js
  52. 1
    1
      service/RTC/Resolutions.js
  53. 1
    1
      service/RTC/StreamEventTypes.js
  54. 1
    1
      service/RTC/VideoType.js
  55. 1
    1
      service/authentication/AuthenticationEvents.js
  56. 1
    1
      service/statistics/constants.js
  57. 1
    1
      service/xmpp/XMPPEvents.js
  58. 5
    5
      webpack.config.js

+ 3
- 0
.eslintignore Visa fil

13
 # not seem to be a reason why we will want to risk being inconsistent with our
13
 # not seem to be a reason why we will want to risk being inconsistent with our
14
 # remaining JavaScript source code.
14
 # remaining JavaScript source code.
15
 !.eslintrc.js
15
 !.eslintrc.js
16
+
17
+# Source code written in ES5 which is not processed through Babel.
18
+connection_optimization/external_connect.js

+ 1
- 0
.eslintrc.js Visa fil

199
         'no-useless-computed-key': 2,
199
         'no-useless-computed-key': 2,
200
         'no-useless-constructor': 2,
200
         'no-useless-constructor': 2,
201
         'no-useless-rename': 2,
201
         'no-useless-rename': 2,
202
+        'no-var': 2,
202
         'object-shorthand': [
203
         'object-shorthand': [
203
             'error',
204
             'error',
204
             'always',
205
             'always',

+ 26
- 26
JitsiConference.js Visa fil

37
  */
37
  */
38
 function JitsiConference(options) {
38
 function JitsiConference(options) {
39
     if (!options.name || options.name.toLowerCase() !== options.name) {
39
     if (!options.name || options.name.toLowerCase() !== options.name) {
40
-        var errmsg
40
+        const errmsg
41
             = 'Invalid conference name (no conference name passed or it '
41
             = 'Invalid conference name (no conference name passed or it '
42
                 + 'contains invalid characters like capital letters)!';
42
                 + 'contains invalid characters like capital letters)!';
43
         logger.error(errmsg);
43
         logger.error(errmsg);
438
 JitsiConference.prototype.addTrack = function(track) {
438
 JitsiConference.prototype.addTrack = function(track) {
439
     if (track.isVideoTrack()) {
439
     if (track.isVideoTrack()) {
440
         // Ensure there's exactly 1 local video track in the conference.
440
         // Ensure there's exactly 1 local video track in the conference.
441
-        var localVideoTrack = this.rtc.getLocalVideoTrack();
441
+        const localVideoTrack = this.rtc.getLocalVideoTrack();
442
         if (localVideoTrack) {
442
         if (localVideoTrack) {
443
             // Don't be excessively harsh and severe if the API client happens
443
             // Don't be excessively harsh and severe if the API client happens
444
             // to attempt to add the same local video track twice.
444
             // to attempt to add the same local video track twice.
589
     if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
589
     if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
590
             && newTrack.videoType !== VideoType.DESKTOP)) {
590
             && newTrack.videoType !== VideoType.DESKTOP)) {
591
         // Report active device to statistics
591
         // Report active device to statistics
592
-        var devices = RTC.getCurrentlyAvailableMediaDevices();
593
-        var device = devices.find(function(d) {
592
+        const devices = RTC.getCurrentlyAvailableMediaDevices();
593
+        const device = devices.find(function(d) {
594
             return d.kind === newTrack.getTrack().kind + 'input'
594
             return d.kind === newTrack.getTrack().kind + 'input'
595
                 && d.label === newTrack.getTrack().label;
595
                 && d.label === newTrack.getTrack().label;
596
         });
596
         });
724
         return Promise.reject();
724
         return Promise.reject();
725
     }
725
     }
726
 
726
 
727
-    var conference = this;
727
+    const conference = this;
728
     return new Promise(function(resolve, reject) {
728
     return new Promise(function(resolve, reject) {
729
         conference.room.lockRoom(password || '', function() {
729
         conference.room.lockRoom(password || '', function() {
730
             resolve();
730
             resolve();
825
  * @param {string} id id of the participant to kick
825
  * @param {string} id id of the participant to kick
826
  */
826
  */
827
 JitsiConference.prototype.kickParticipant = function(id) {
827
 JitsiConference.prototype.kickParticipant = function(id) {
828
-    var participant = this.getParticipantById(id);
828
+    const participant = this.getParticipantById(id);
829
     if (!participant) {
829
     if (!participant) {
830
         return;
830
         return;
831
     }
831
     }
837
  * @param {string} id The id of the participant to mute.
837
  * @param {string} id The id of the participant to mute.
838
  */
838
  */
839
 JitsiConference.prototype.muteParticipant = function(id) {
839
 JitsiConference.prototype.muteParticipant = function(id) {
840
-    var participant = this.getParticipantById(id);
840
+    const participant = this.getParticipantById(id);
841
     if (!participant) {
841
     if (!participant) {
842
         return;
842
         return;
843
     }
843
     }
857
  */
857
  */
858
 JitsiConference.prototype.onMemberJoined
858
 JitsiConference.prototype.onMemberJoined
859
     = function(jid, nick, role, isHidden) {
859
     = function(jid, nick, role, isHidden) {
860
-        var id = Strophe.getResourceFromJid(jid);
860
+        const id = Strophe.getResourceFromJid(jid);
861
         if (id === 'focus' || this.myUserId() === id) {
861
         if (id === 'focus' || this.myUserId() === id) {
862
             return;
862
             return;
863
         }
863
         }
864
-        var participant = new JitsiParticipant(jid, this, nick, isHidden);
864
+        const participant = new JitsiParticipant(jid, this, nick, isHidden);
865
         participant._role = role;
865
         participant._role = role;
866
         this.participants[id] = participant;
866
         this.participants[id] = participant;
867
         this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
867
         this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
872
     };
872
     };
873
 
873
 
874
 JitsiConference.prototype.onMemberLeft = function(jid) {
874
 JitsiConference.prototype.onMemberLeft = function(jid) {
875
-    var id = Strophe.getResourceFromJid(jid);
875
+    const id = Strophe.getResourceFromJid(jid);
876
     if (id === 'focus' || this.myUserId() === id) {
876
     if (id === 'focus' || this.myUserId() === id) {
877
         return;
877
         return;
878
     }
878
     }
879
-    var participant = this.participants[id];
879
+    const participant = this.participants[id];
880
     delete this.participants[id];
880
     delete this.participants[id];
881
 
881
 
882
-    var removedTracks = this.rtc.removeRemoteTracks(id);
882
+    const removedTracks = this.rtc.removeRemoteTracks(id);
883
 
883
 
884
     removedTracks.forEach(function(track) {
884
     removedTracks.forEach(function(track) {
885
         this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
885
         this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
893
 };
893
 };
894
 
894
 
895
 JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
895
 JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
896
-    var id = Strophe.getResourceFromJid(jid);
897
-    var participant = this.getParticipantById(id);
896
+    const id = Strophe.getResourceFromJid(jid);
897
+    const participant = this.getParticipantById(id);
898
     if (!participant) {
898
     if (!participant) {
899
         return;
899
         return;
900
     }
900
     }
903
 };
903
 };
904
 
904
 
905
 JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
905
 JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
906
-    var id = Strophe.getResourceFromJid(jid);
907
-    var participant = this.getParticipantById(id);
906
+    const id = Strophe.getResourceFromJid(jid);
907
+    const participant = this.getParticipantById(id);
908
     if (!participant) {
908
     if (!participant) {
909
         return;
909
         return;
910
     }
910
     }
1007
 = function(jingleSession, jingleOffer, now) {
1007
 = function(jingleSession, jingleOffer, now) {
1008
     if (!this.room.isFocus(jingleSession.peerjid)) {
1008
     if (!this.room.isFocus(jingleSession.peerjid)) {
1009
         // Error cause this should never happen unless something is wrong!
1009
         // Error cause this should never happen unless something is wrong!
1010
-        var errmsg = 'Rejecting session-initiate from non-focus user: '
1010
+        const errmsg = 'Rejecting session-initiate from non-focus user: '
1011
                 + jingleSession.peerjid;
1011
                 + jingleSession.peerjid;
1012
         GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
1012
         GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
1013
         logger.error(errmsg);
1013
         logger.error(errmsg);
1033
         Statistics.sendEventToAll('session.restart');
1033
         Statistics.sendEventToAll('session.restart');
1034
     }
1034
     }
1035
     // add info whether call is cross-region
1035
     // add info whether call is cross-region
1036
-    var crossRegion = null;
1036
+    let crossRegion = null;
1037
     if (window.jitsiRegionInfo) {
1037
     if (window.jitsiRegionInfo) {
1038
         crossRegion = window.jitsiRegionInfo.CrossRegion;
1038
         crossRegion = window.jitsiRegionInfo.CrossRegion;
1039
     }
1039
     }
1146
     // We want to re-register 'ssrcHandler' of our local tracks, so that they
1146
     // We want to re-register 'ssrcHandler' of our local tracks, so that they
1147
     // will learn what their SSRC from the new PeerConnection which will be
1147
     // will learn what their SSRC from the new PeerConnection which will be
1148
     // created on incoming call event.
1148
     // created on incoming call event.
1149
-    var self = this;
1149
+    const self = this;
1150
     this.getLocalTracks().forEach(function(localTrack) {
1150
     this.getLocalTracks().forEach(function(localTrack) {
1151
         // Reset SSRC as it will no longer be valid
1151
         // Reset SSRC as it will no longer be valid
1152
         localTrack._setSSRC(null);
1152
         localTrack._setSSRC(null);
1166
 };
1166
 };
1167
 
1167
 
1168
 JitsiConference.prototype.updateDTMFSupport = function() {
1168
 JitsiConference.prototype.updateDTMFSupport = function() {
1169
-    var somebodySupportsDTMF = false;
1170
-    var participants = this.getParticipants();
1169
+    let somebodySupportsDTMF = false;
1170
+    const participants = this.getParticipants();
1171
 
1171
 
1172
     // check if at least 1 participant supports DTMF
1172
     // check if at least 1 participant supports DTMF
1173
-    for (var i = 0; i < participants.length; i += 1) {
1173
+    for (let i = 0; i < participants.length; i += 1) {
1174
         if (participants[i].supportsDTMF()) {
1174
         if (participants[i].supportsDTMF()) {
1175
             somebodySupportsDTMF = true;
1175
             somebodySupportsDTMF = true;
1176
             break;
1176
             break;
1379
  * Get object with internal logs.
1379
  * Get object with internal logs.
1380
  */
1380
  */
1381
 JitsiConference.prototype.getLogs = function() {
1381
 JitsiConference.prototype.getLogs = function() {
1382
-    var data = this.xmpp.getJingleLog();
1382
+    const data = this.xmpp.getJingleLog();
1383
 
1383
 
1384
-    var metadata = {};
1384
+    const metadata = {};
1385
     metadata.time = new Date();
1385
     metadata.time = new Date();
1386
     metadata.url = window.location.href;
1386
     metadata.url = window.location.href;
1387
     metadata.ua = navigator.userAgent;
1387
     metadata.ua = navigator.userAgent;
1388
 
1388
 
1389
-    var log = this.xmpp.getXmppLog();
1389
+    const log = this.xmpp.getXmppLog();
1390
     if (log) {
1390
     if (log) {
1391
         metadata.xmpp = log;
1391
         metadata.xmpp = log;
1392
     }
1392
     }
1441
  * @param container the container
1441
  * @param container the container
1442
  */
1442
  */
1443
 JitsiConference.prototype._onTrackAttach = function(track, container) {
1443
 JitsiConference.prototype._onTrackAttach = function(track, container) {
1444
-    var ssrc = track.getSSRC();
1444
+    const ssrc = track.getSSRC();
1445
     if (!container.id || !ssrc) {
1445
     if (!container.id || !ssrc) {
1446
         return;
1446
         return;
1447
     }
1447
     }

+ 27
- 27
JitsiConferenceEventManager.js Visa fil

35
  * Setups event listeners related to conference.chatRoom
35
  * Setups event listeners related to conference.chatRoom
36
  */
36
  */
37
 JitsiConferenceEventManager.prototype.setupChatRoomListeners = function() {
37
 JitsiConferenceEventManager.prototype.setupChatRoomListeners = function() {
38
-    var conference = this.conference;
39
-    var chatRoom = conference.room;
38
+    const conference = this.conference;
39
+    const chatRoom = conference.room;
40
     this.chatRoomForwarder = new EventEmitterForwarder(chatRoom,
40
     this.chatRoomForwarder = new EventEmitterForwarder(chatRoom,
41
         this.conference.eventEmitter);
41
         this.conference.eventEmitter);
42
 
42
 
156
                 JitsiConferenceErrors.FOCUS_LEFT);
156
                 JitsiConferenceErrors.FOCUS_LEFT);
157
         });
157
         });
158
 
158
 
159
-    var eventLogHandler = function(reason) {
159
+    const eventLogHandler = function(reason) {
160
         Statistics.sendEventToAll('conference.error.' + reason);
160
         Statistics.sendEventToAll('conference.error.' + reason);
161
     };
161
     };
162
     chatRoom.addListener(XMPPEvents.SESSION_ACCEPT_TIMEOUT,
162
     chatRoom.addListener(XMPPEvents.SESSION_ACCEPT_TIMEOUT,
189
         JitsiConferenceErrors.SETUP_FAILED);
189
         JitsiConferenceErrors.SETUP_FAILED);
190
 
190
 
191
     chatRoom.setParticipantPropertyListener(function(node, from) {
191
     chatRoom.setParticipantPropertyListener(function(node, from) {
192
-        var participant = conference.getParticipantById(from);
192
+        const participant = conference.getParticipantById(from);
193
         if (!participant) {
193
         if (!participant) {
194
             return;
194
             return;
195
         }
195
         }
230
         if (conference.statistics && conference.isModerator()) {
230
         if (conference.statistics && conference.isModerator()) {
231
             conference.on(JitsiConferenceEvents.RECORDER_STATE_CHANGED,
231
             conference.on(JitsiConferenceEvents.RECORDER_STATE_CHANGED,
232
                 function(status, error) {
232
                 function(status, error) {
233
-                    var logObject = {
233
+                    const logObject = {
234
                         id: 'recorder_status',
234
                         id: 'recorder_status',
235
                         status
235
                         status
236
                     };
236
                     };
256
 
256
 
257
     chatRoom.addListener(XMPPEvents.MESSAGE_RECEIVED,
257
     chatRoom.addListener(XMPPEvents.MESSAGE_RECEIVED,
258
         function(jid, displayName, txt, myJid, ts) {
258
         function(jid, displayName, txt, myJid, ts) {
259
-            var id = Strophe.getResourceFromJid(jid);
259
+            const id = Strophe.getResourceFromJid(jid);
260
             conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED,
260
             conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED,
261
                 id, txt, ts);
261
                 id, txt, ts);
262
         });
262
         });
263
 
263
 
264
     chatRoom.addListener(XMPPEvents.PRESENCE_STATUS,
264
     chatRoom.addListener(XMPPEvents.PRESENCE_STATUS,
265
         function(jid, status) {
265
         function(jid, status) {
266
-            var id = Strophe.getResourceFromJid(jid);
267
-            var participant = conference.getParticipantById(id);
266
+            const id = Strophe.getResourceFromJid(jid);
267
+            const participant = conference.getParticipantById(id);
268
             if (!participant || participant._status === status) {
268
             if (!participant || participant._status === status) {
269
                 return;
269
                 return;
270
             }
270
             }
285
         });
285
         });
286
 
286
 
287
     chatRoom.addPresenceListener('startmuted', function(data, from) {
287
     chatRoom.addPresenceListener('startmuted', function(data, from) {
288
-        var isModerator = false;
288
+        let isModerator = false;
289
         if (conference.myUserId() === from && conference.isModerator()) {
289
         if (conference.myUserId() === from && conference.isModerator()) {
290
             isModerator = true;
290
             isModerator = true;
291
         } else {
291
         } else {
292
-            var participant = conference.getParticipantById(from);
292
+            const participant = conference.getParticipantById(from);
293
             if (participant && participant.isModerator()) {
293
             if (participant && participant.isModerator()) {
294
                 isModerator = true;
294
                 isModerator = true;
295
             }
295
             }
299
             return;
299
             return;
300
         }
300
         }
301
 
301
 
302
-        var startAudioMuted = data.attributes.audio === 'true';
303
-        var startVideoMuted = data.attributes.video === 'true';
302
+        const startAudioMuted = data.attributes.audio === 'true';
303
+        const startVideoMuted = data.attributes.video === 'true';
304
 
304
 
305
-        var updated = false;
305
+        let updated = false;
306
 
306
 
307
         if (startAudioMuted !== conference.startMutedPolicy.audio) {
307
         if (startAudioMuted !== conference.startMutedPolicy.audio) {
308
             conference.startMutedPolicy.audio = startAudioMuted;
308
             conference.startMutedPolicy.audio = startAudioMuted;
337
     });
337
     });
338
 
338
 
339
     chatRoom.addPresenceListener('devices', function(data, from) {
339
     chatRoom.addPresenceListener('devices', function(data, from) {
340
-        var isAudioAvailable = false;
341
-        var isVideoAvailable = false;
340
+        let isAudioAvailable = false;
341
+        let isVideoAvailable = false;
342
         data.children.forEach(function(config) {
342
         data.children.forEach(function(config) {
343
             if (config.tagName === 'audio') {
343
             if (config.tagName === 'audio') {
344
                 isAudioAvailable = config.value === 'true';
344
                 isAudioAvailable = config.value === 'true';
348
             }
348
             }
349
         });
349
         });
350
 
350
 
351
-        var availableDevices;
351
+        let availableDevices;
352
         if (conference.myUserId() === from) {
352
         if (conference.myUserId() === from) {
353
             availableDevices = conference.availableDevices;
353
             availableDevices = conference.availableDevices;
354
         } else {
354
         } else {
355
-            var participant = conference.getParticipantById(from);
355
+            const participant = conference.getParticipantById(from);
356
             if (!participant) {
356
             if (!participant) {
357
                 return;
357
                 return;
358
             }
358
             }
360
             availableDevices = participant._availableDevices;
360
             availableDevices = participant._availableDevices;
361
         }
361
         }
362
 
362
 
363
-        var updated = false;
363
+        let updated = false;
364
 
364
 
365
         if (availableDevices.audio !== isAudioAvailable) {
365
         if (availableDevices.audio !== isAudioAvailable) {
366
             updated = true;
366
             updated = true;
424
         });
424
         });
425
 
425
 
426
     rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
426
     rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
427
-        var now = window.performance.now();
427
+        const now = window.performance.now();
428
         logger.log('(TIME) data channel opened ', now);
428
         logger.log('(TIME) data channel opened ', now);
429
         conference.room.connectionTimes['data.channel.opened'] = now;
429
         conference.room.connectionTimes['data.channel.opened'] = now;
430
         Statistics.analytics.sendEvent('conference.dataChannel.open',
430
         Statistics.analytics.sendEvent('conference.dataChannel.open',
483
  * Setups event listeners related to conference.xmpp
483
  * Setups event listeners related to conference.xmpp
484
  */
484
  */
485
 JitsiConferenceEventManager.prototype.setupXMPPListeners = function() {
485
 JitsiConferenceEventManager.prototype.setupXMPPListeners = function() {
486
-    var conference = this.conference;
486
+    const conference = this.conference;
487
     conference.xmpp.caps.addListener(XMPPEvents.PARTCIPANT_FEATURES_CHANGED,
487
     conference.xmpp.caps.addListener(XMPPEvents.PARTCIPANT_FEATURES_CHANGED,
488
         from => {
488
         from => {
489
             const participant = conference.getParticipantId(
489
             const participant = conference.getParticipantId(
525
  * Setups event listeners related to conference.statistics
525
  * Setups event listeners related to conference.statistics
526
  */
526
  */
527
 JitsiConferenceEventManager.prototype.setupStatisticsListeners = function() {
527
 JitsiConferenceEventManager.prototype.setupStatisticsListeners = function() {
528
-    var conference = this.conference;
528
+    const conference = this.conference;
529
     if(!conference.statistics) {
529
     if(!conference.statistics) {
530
         return;
530
         return;
531
     }
531
     }
532
 
532
 
533
     conference.statistics.addAudioLevelListener(function(ssrc, level) {
533
     conference.statistics.addAudioLevelListener(function(ssrc, level) {
534
-        var resource = conference.rtc.getResourceBySSRC(ssrc);
534
+        const resource = conference.rtc.getResourceBySSRC(ssrc);
535
         if (!resource) {
535
         if (!resource) {
536
             return;
536
             return;
537
         }
537
         }
544
             JitsiConferenceEvents.BEFORE_STATISTICS_DISPOSED);
544
             JitsiConferenceEvents.BEFORE_STATISTICS_DISPOSED);
545
     });
545
     });
546
     conference.statistics.addConnectionStatsListener(function(stats) {
546
     conference.statistics.addConnectionStatsListener(function(stats) {
547
-        var ssrc2resolution = stats.resolution;
547
+        const ssrc2resolution = stats.resolution;
548
 
548
 
549
-        var id2resolution = {};
549
+        const id2resolution = {};
550
 
550
 
551
         // preprocess resolutions: group by user id, skip incorrect
551
         // preprocess resolutions: group by user id, skip incorrect
552
         // resolutions etc.
552
         // resolutions etc.
553
         Object.keys(ssrc2resolution).forEach(function(ssrc) {
553
         Object.keys(ssrc2resolution).forEach(function(ssrc) {
554
-            var resolution = ssrc2resolution[ssrc];
554
+            const resolution = ssrc2resolution[ssrc];
555
 
555
 
556
             if (!resolution.width || !resolution.height
556
             if (!resolution.width || !resolution.height
557
                 || resolution.width == -1 || resolution.height == -1) {
557
                 || resolution.width == -1 || resolution.height == -1) {
558
                 return;
558
                 return;
559
             }
559
             }
560
 
560
 
561
-            var id = conference.rtc.getResourceBySSRC(ssrc);
561
+            const id = conference.rtc.getResourceBySSRC(ssrc);
562
             if (!id) {
562
             if (!id) {
563
                 return;
563
                 return;
564
             }
564
             }
565
 
565
 
566
             // ssrc to resolution map for user id
566
             // ssrc to resolution map for user id
567
-            var idResolutions = id2resolution[id] || {};
567
+            const idResolutions = id2resolution[id] || {};
568
             idResolutions[ssrc] = resolution;
568
             idResolutions[ssrc] = resolution;
569
 
569
 
570
             id2resolution[id] = idResolutions;
570
             id2resolution[id] = idResolutions;

+ 3
- 3
JitsiConnection.js Visa fil

1
-var JitsiConference = require('./JitsiConference');
1
+const JitsiConference = require('./JitsiConference');
2
 import * as JitsiConnectionEvents from './JitsiConnectionEvents';
2
 import * as JitsiConnectionEvents from './JitsiConnectionEvents';
3
 import XMPP from './modules/xmpp/xmpp';
3
 import XMPP from './modules/xmpp/xmpp';
4
-var Statistics = require('./modules/statistics/statistics');
4
+const Statistics = require('./modules/statistics/statistics');
5
 
5
 
6
 /**
6
 /**
7
  * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
7
  * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
70
     // XMPP.disconnect. For example, the caller of JitsiConnection.disconnect
70
     // XMPP.disconnect. For example, the caller of JitsiConnection.disconnect
71
     // may optionally pass the event which triggered the disconnect in order to
71
     // may optionally pass the event which triggered the disconnect in order to
72
     // provide the implementation with finer-grained context.
72
     // provide the implementation with finer-grained context.
73
-    var x = this.xmpp;
73
+    const x = this.xmpp;
74
 
74
 
75
     x.disconnect(...arguments);
75
     x.disconnect(...arguments);
76
 };
76
 };

+ 4
- 4
JitsiMediaDevices.js Visa fil

26
  * @param devices list of devices
26
  * @param devices list of devices
27
  */
27
  */
28
 function logOutputDevice(deviceID, devices) {
28
 function logOutputDevice(deviceID, devices) {
29
-    var device = devices.find(function(d) {
29
+    const device = devices.find(function(d) {
30
         return d.kind === 'audiooutput' && d.deviceId === deviceID;
30
         return d.kind === 'audiooutput' && d.deviceId === deviceID;
31
     });
31
     });
32
 
32
 
36
     }
36
     }
37
 }
37
 }
38
 
38
 
39
-var JitsiMediaDevices = {
39
+const JitsiMediaDevices = {
40
     /**
40
     /**
41
      * Executes callback with list of media devices connected.
41
      * Executes callback with list of media devices connected.
42
      * @param {function} callback
42
      * @param {function} callback
70
      * @returns {boolean}
70
      * @returns {boolean}
71
      */
71
      */
72
     isDevicePermissionGranted(type) {
72
     isDevicePermissionGranted(type) {
73
-        var permissions = RTC.getDeviceAvailability();
73
+        const permissions = RTC.getDeviceAvailability();
74
 
74
 
75
         switch(type) {
75
         switch(type) {
76
         case MediaType.VIDEO:
76
         case MediaType.VIDEO:
99
      */
99
      */
100
     setAudioOutputDevice(deviceId) {
100
     setAudioOutputDevice(deviceId) {
101
 
101
 
102
-        var availableDevices = RTC.getCurrentlyAvailableMediaDevices();
102
+        const availableDevices = RTC.getCurrentlyAvailableMediaDevices();
103
         if (availableDevices && availableDevices.length > 0) {
103
         if (availableDevices && availableDevices.length > 0) {
104
             // if we have devices info report device to stats
104
             // if we have devices info report device to stats
105
             // normally this will not happen on startup as this method is called
105
             // normally this will not happen on startup as this method is called

+ 8
- 8
JitsiMeetJS.js Visa fil

28
 
28
 
29
 // The amount of time to wait until firing
29
 // The amount of time to wait until firing
30
 // JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN event
30
 // JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN event
31
-var USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 500;
31
+const USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 500;
32
 
32
 
33
 function getLowerResolution(resolution) {
33
 function getLowerResolution(resolution) {
34
     if(!Resolutions[resolution]) {
34
     if(!Resolutions[resolution]) {
35
         return null;
35
         return null;
36
     }
36
     }
37
-    var order = Resolutions[resolution].order;
38
-    var res = null;
39
-    var resName = null;
37
+    const order = Resolutions[resolution].order;
38
+    let res = null;
39
+    let resName = null;
40
     Object.keys(Resolutions).forEach(resolution => {
40
     Object.keys(Resolutions).forEach(resolution => {
41
         const value = Resolutions[resolution];
41
         const value = Resolutions[resolution];
42
         if (!res || (res.order < value.order && value.order < order)) {
42
         if (!res || (res.order < value.order && value.order < order)) {
73
 /**
73
 /**
74
  * Namespace for the interface of Jitsi Meet Library.
74
  * Namespace for the interface of Jitsi Meet Library.
75
  */
75
  */
76
-var LibJitsiMeet = {
76
+const LibJitsiMeet = {
77
 
77
 
78
     version: '{#COMMIT_HASH#}',
78
     version: '{#COMMIT_HASH#}',
79
 
79
 
211
      *     or a JitsiConferenceError if rejected.
211
      *     or a JitsiConferenceError if rejected.
212
      */
212
      */
213
     createLocalTracks(options, firePermissionPromptIsShownEvent) {
213
     createLocalTracks(options, firePermissionPromptIsShownEvent) {
214
-        var promiseFulfilled = false;
214
+        let promiseFulfilled = false;
215
 
215
 
216
         if (firePermissionPromptIsShownEvent === true) {
216
         if (firePermissionPromptIsShownEvent === true) {
217
             window.setTimeout(function() {
217
             window.setTimeout(function() {
242
                 if(!RTC.options.disableAudioLevels) {
242
                 if(!RTC.options.disableAudioLevels) {
243
                     for(let i = 0; i < tracks.length; i++) {
243
                     for(let i = 0; i < tracks.length; i++) {
244
                         const track = tracks[i];
244
                         const track = tracks[i];
245
-                        var mStream = track.getOriginalStream();
245
+                        const mStream = track.getOriginalStream();
246
                         if(track.getType() === MediaType.AUDIO) {
246
                         if(track.getType() === MediaType.AUDIO) {
247
                             Statistics.startLocalStats(mStream,
247
                             Statistics.startLocalStats(mStream,
248
                                 track.setAudioLevel.bind(track));
248
                                 track.setAudioLevel.bind(track));
256
                 }
256
                 }
257
 
257
 
258
                 // set real device ids
258
                 // set real device ids
259
-                var currentlyAvailableMediaDevices
259
+                const currentlyAvailableMediaDevices
260
                     = RTC.getCurrentlyAvailableMediaDevices();
260
                     = RTC.getCurrentlyAvailableMediaDevices();
261
                 if (currentlyAvailableMediaDevices) {
261
                 if (currentlyAvailableMediaDevices) {
262
                     for(let i = 0; i < tracks.length; i++) {
262
                     for(let i = 0; i < tracks.length; i++) {

+ 1
- 1
JitsiParticipant.js Visa fil

91
      * @value the value to set.
91
      * @value the value to set.
92
      */
92
      */
93
     setProperty(name, value) {
93
     setProperty(name, value) {
94
-        var oldValue = this._properties[name];
94
+        const oldValue = this._properties[name];
95
 
95
 
96
         if (value !== oldValue) {
96
         if (value !== oldValue) {
97
             this._properties[name] = value;
97
             this._properties[name] = value;

+ 1
- 1
JitsiRecorderErrors.js Visa fil

2
  * Enumeration with the errors for the conference.
2
  * Enumeration with the errors for the conference.
3
  * @type {{string: string}}
3
  * @type {{string: string}}
4
  */
4
  */
5
-var JitsiRecorderErrors = {
5
+const JitsiRecorderErrors = {
6
     /**
6
     /**
7
      * Indicates that the recorder is currently unavailable.
7
      * Indicates that the recorder is currently unavailable.
8
      */
8
      */

+ 4
- 2
JitsiTrackError.js Visa fil

83
                     + (this.gum.devices || []).join(', ');
83
                     + (this.gum.devices || []).join(', ');
84
             break;
84
             break;
85
         case 'ConstraintNotSatisfiedError':
85
         case 'ConstraintNotSatisfiedError':
86
-        case 'OverconstrainedError':
87
-            var constraintName = error.constraintName;
86
+        case 'OverconstrainedError': {
87
+            const constraintName = error.constraintName;
88
 
88
 
89
             if (options
89
             if (options
90
                     && options.video
90
                     && options.video
108
                         + error.constraintName;
108
                         + error.constraintName;
109
             }
109
             }
110
             break;
110
             break;
111
+        }
112
+
111
         default:
113
         default:
112
             this.name = JitsiTrackErrors.GENERAL;
114
             this.name = JitsiTrackErrors.GENERAL;
113
             this.message
115
             this.message

+ 19
- 19
doc/example/example.js Visa fil

1
 /* global $, JitsiMeetJS */
1
 /* global $, JitsiMeetJS */
2
 
2
 
3
-var options = {
3
+const options = {
4
     hosts: {
4
     hosts: {
5
         domain: 'jitsi-meet.example.com',
5
         domain: 'jitsi-meet.example.com',
6
         muc: 'conference.jitsi-meet.example.com', // FIXME: use XEP-0030
6
         muc: 'conference.jitsi-meet.example.com', // FIXME: use XEP-0030
9
     clientNode: 'http://jitsi.org/jitsimeet', // The name of client node advertised in XEP-0115 'c' stanza
9
     clientNode: 'http://jitsi.org/jitsimeet', // The name of client node advertised in XEP-0115 'c' stanza
10
 };
10
 };
11
 
11
 
12
-var confOptions = {
12
+const confOptions = {
13
     openSctp: true
13
     openSctp: true
14
 };
14
 };
15
 
15
 
16
-var isJoined = false;
16
+let connection = null;
17
+let isJoined = false;
18
+let room = null;
19
+
20
+let localTracks = [];
21
+const remoteTracks = {};
17
 
22
 
18
 /**
23
 /**
19
  * Handles local tracks.
24
  * Handles local tracks.
21
  */
26
  */
22
 function onLocalTracks(tracks) {
27
 function onLocalTracks(tracks) {
23
     localTracks = tracks;
28
     localTracks = tracks;
24
-    for(var i = 0; i < localTracks.length; i++) {
29
+    for(let i = 0; i < localTracks.length; i++) {
25
         localTracks[i].addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
30
         localTracks[i].addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
26
             function(audioLevel) {
31
             function(audioLevel) {
27
                 console.log('Audio Level local: ' + audioLevel);
32
                 console.log('Audio Level local: ' + audioLevel);
59
     if(track.isLocal()) {
64
     if(track.isLocal()) {
60
         return;
65
         return;
61
     }
66
     }
62
-    var participant = track.getParticipantId();
67
+    const participant = track.getParticipantId();
63
     if(!remoteTracks[participant]) {
68
     if(!remoteTracks[participant]) {
64
         remoteTracks[participant] = [];
69
         remoteTracks[participant] = [];
65
     }
70
     }
66
-    var idx = remoteTracks[participant].push(track);
71
+    const idx = remoteTracks[participant].push(track);
67
     track.addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
72
     track.addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
68
         function(audioLevel) {
73
         function(audioLevel) {
69
             console.log('Audio Level remote: ' + audioLevel);
74
             console.log('Audio Level remote: ' + audioLevel);
80
         function(deviceId) {
85
         function(deviceId) {
81
             console.log('track audio output device was changed to ' + deviceId);
86
             console.log('track audio output device was changed to ' + deviceId);
82
         });
87
         });
83
-    var id = participant + track.getType() + idx;
88
+    const id = participant + track.getType() + idx;
84
     if(track.getType() == 'video') {
89
     if(track.getType() == 'video') {
85
         $('body').append('<video autoplay=\'1\' id=\'' + participant + 'video' + idx + '\' />');
90
         $('body').append('<video autoplay=\'1\' id=\'' + participant + 'video' + idx + '\' />');
86
     } else {
91
     } else {
95
 function onConferenceJoined() {
100
 function onConferenceJoined() {
96
     console.log('conference joined!');
101
     console.log('conference joined!');
97
     isJoined = true;
102
     isJoined = true;
98
-    for(var i = 0; i < localTracks.length; i++) {
103
+    for(let i = 0; i < localTracks.length; i++) {
99
         room.addTrack(localTracks[i]);
104
         room.addTrack(localTracks[i]);
100
     }
105
     }
101
 }
106
 }
105
     if(!remoteTracks[id]) {
110
     if(!remoteTracks[id]) {
106
         return;
111
         return;
107
     }
112
     }
108
-    var tracks = remoteTracks[id];
109
-    for(var i = 0; i < tracks.length; i++) {
113
+    const tracks = remoteTracks[id];
114
+    for(let i = 0; i < tracks.length; i++) {
110
         tracks[i].detach($('#' + id + tracks[i].getType()));
115
         tracks[i].detach($('#' + id + tracks[i].getType()));
111
     }
116
     }
112
 }
117
 }
173
 }
178
 }
174
 
179
 
175
 function unload() {
180
 function unload() {
176
-    for(var i = 0; i < localTracks.length; i++) {
181
+    for(let i = 0; i < localTracks.length; i++) {
177
         localTracks[i].stop();
182
         localTracks[i].stop();
178
     }
183
     }
179
     room.leave();
184
     room.leave();
180
     connection.disconnect();
185
     connection.disconnect();
181
 }
186
 }
182
 
187
 
183
-var isVideo = true;
188
+let isVideo = true;
184
 function switchVideo() { // eslint-disable-line no-unused-vars
189
 function switchVideo() { // eslint-disable-line no-unused-vars
185
     isVideo = !isVideo;
190
     isVideo = !isVideo;
186
     if(localTracks[1]) {
191
     if(localTracks[1]) {
213
 $(window).bind('unload', unload);
218
 $(window).bind('unload', unload);
214
 
219
 
215
 // JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.ERROR);
220
 // JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.ERROR);
216
-var initOptions = {
221
+const initOptions = {
217
     disableAudioLevels: true,
222
     disableAudioLevels: true,
218
     // The ID of the jidesha extension for Chrome.
223
     // The ID of the jidesha extension for Chrome.
219
     desktopSharingChromeExtId: 'mbocklcggfhnbahlnepmldehdhpjfcjp',
224
     desktopSharingChromeExtId: 'mbocklcggfhnbahlnepmldehdhpjfcjp',
259
 
264
 
260
 if (JitsiMeetJS.mediaDevices.isDeviceChangeAvailable('output')) {
265
 if (JitsiMeetJS.mediaDevices.isDeviceChangeAvailable('output')) {
261
     JitsiMeetJS.mediaDevices.enumerateDevices(function(devices) {
266
     JitsiMeetJS.mediaDevices.enumerateDevices(function(devices) {
262
-        var audioOutputDevices = devices.filter(function(d) {
267
+        const audioOutputDevices = devices.filter(function(d) {
263
             return d.kind === 'audiooutput';
268
             return d.kind === 'audiooutput';
264
         });
269
         });
265
 
270
 
274
         }
279
         }
275
     });
280
     });
276
 }
281
 }
277
-
278
-var connection = null;
279
-var room = null;
280
-var localTracks = [];
281
-var remoteTracks = {};

+ 2
- 2
modules/DTMF/JitsiDTMFManager.js Visa fil

1
-var logger = require('jitsi-meet-logger').getLogger(__filename);
1
+const logger = require('jitsi-meet-logger').getLogger(__filename);
2
 
2
 
3
 function JitsiDTMFManager(localAudio, peerConnection) {
3
 function JitsiDTMFManager(localAudio, peerConnection) {
4
-    var audioTrack = localAudio.getTrack();
4
+    const audioTrack = localAudio.getTrack();
5
     if (!audioTrack) {
5
     if (!audioTrack) {
6
         throw new Error('Failed to initialize DTMFSender: no audio track.');
6
         throw new Error('Failed to initialize DTMFSender: no audio track.');
7
     }
7
     }

+ 23
- 23
modules/RTC/DataChannels.js Visa fil

1
 // cache datachannels to avoid garbage collection
1
 // cache datachannels to avoid garbage collection
2
 // https://code.google.com/p/chromium/issues/detail?id=405545
2
 // https://code.google.com/p/chromium/issues/detail?id=405545
3
 
3
 
4
-var logger = require('jitsi-meet-logger').getLogger(__filename);
5
-var RTCEvents = require('../../service/RTC/RTCEvents');
6
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
+const logger = require('jitsi-meet-logger').getLogger(__filename);
5
+const RTCEvents = require('../../service/RTC/RTCEvents');
6
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
7
 
7
 
8
 /**
8
 /**
9
  * Binds "ondatachannel" event listener to given PeerConnection instance.
9
  * Binds "ondatachannel" event listener to given PeerConnection instance.
45
  * @param event the event info object.
45
  * @param event the event info object.
46
  */
46
  */
47
 DataChannels.prototype.onDataChannel = function(event) {
47
 DataChannels.prototype.onDataChannel = function(event) {
48
-    var dataChannel = event.channel;
49
-    var self = this;
48
+    const dataChannel = event.channel;
49
+    const self = this;
50
 
50
 
51
     dataChannel.onopen = function() {
51
     dataChannel.onopen = function() {
52
         logger.info('Data channel opened by the Videobridge!', dataChannel);
52
         logger.info('Data channel opened by the Videobridge!', dataChannel);
70
     };
70
     };
71
 
71
 
72
     dataChannel.onmessage = function(event) {
72
     dataChannel.onmessage = function(event) {
73
-        var data = event.data;
73
+        const data = event.data;
74
         // JSON
74
         // JSON
75
-        var obj;
75
+        let obj;
76
 
76
 
77
         try {
77
         try {
78
             obj = JSON.parse(data);
78
             obj = JSON.parse(data);
85
                 e);
85
                 e);
86
         }
86
         }
87
         if (('undefined' !== typeof obj) && (null !== obj)) {
87
         if (('undefined' !== typeof obj) && (null !== obj)) {
88
-            var colibriClass = obj.colibriClass;
88
+            const colibriClass = obj.colibriClass;
89
 
89
 
90
             if ('DominantSpeakerEndpointChangeEvent' === colibriClass) {
90
             if ('DominantSpeakerEndpointChangeEvent' === colibriClass) {
91
                 // Endpoint ID from the Videobridge.
91
                 // Endpoint ID from the Videobridge.
92
-                var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
92
+                const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
93
 
93
 
94
                 logger.info(
94
                 logger.info(
95
                     'Data channel new dominant speaker event: ',
95
                     'Data channel new dominant speaker event: ',
97
                 self.eventEmitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED,
97
                 self.eventEmitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED,
98
                   dominantSpeakerEndpoint);
98
                   dominantSpeakerEndpoint);
99
             } else if ('InLastNChangeEvent' === colibriClass) {
99
             } else if ('InLastNChangeEvent' === colibriClass) {
100
-                var oldValue = obj.oldValue;
101
-                var newValue = obj.newValue;
100
+                let oldValue = obj.oldValue;
101
+                let newValue = obj.newValue;
102
 
102
 
103
                 // Make sure that oldValue and newValue are of type boolean.
103
                 // Make sure that oldValue and newValue are of type boolean.
104
-                var type;
104
+                let type;
105
 
105
 
106
                 if ((type = typeof oldValue) !== 'boolean') {
106
                 if ((type = typeof oldValue) !== 'boolean') {
107
                     if (type === 'string') {
107
                     if (type === 'string') {
121
                 self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
121
                 self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
122
             } else if ('LastNEndpointsChangeEvent' === colibriClass) {
122
             } else if ('LastNEndpointsChangeEvent' === colibriClass) {
123
                 // The new/latest list of last-n endpoint IDs.
123
                 // The new/latest list of last-n endpoint IDs.
124
-                var lastNEndpoints = obj.lastNEndpoints;
124
+                const lastNEndpoints = obj.lastNEndpoints;
125
                 // The list of endpoint IDs which are entering the list of
125
                 // The list of endpoint IDs which are entering the list of
126
                 // last-n at this time i.e. were not in the old list of last-n
126
                 // last-n at this time i.e. were not in the old list of last-n
127
                 // endpoint IDs.
127
                 // endpoint IDs.
128
-                var endpointsEnteringLastN = obj.endpointsEnteringLastN;
128
+                const endpointsEnteringLastN = obj.endpointsEnteringLastN;
129
 
129
 
130
                 logger.info(
130
                 logger.info(
131
                     'Data channel new last-n event: ',
131
                     'Data channel new last-n event: ',
137
                     RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
137
                     RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
138
                     obj.msgPayload);
138
                     obj.msgPayload);
139
             } else if ('EndpointConnectivityStatusChangeEvent' === colibriClass) {
139
             } else if ('EndpointConnectivityStatusChangeEvent' === colibriClass) {
140
-                var endpoint = obj.endpoint;
141
-                var isActive = obj.active === 'true';
140
+                const endpoint = obj.endpoint;
141
+                const isActive = obj.active === 'true';
142
                 logger.info('Endpoint connection status changed: ' + endpoint
142
                 logger.info('Endpoint connection status changed: ' + endpoint
143
                            + ' active ? ' + isActive);
143
                            + ' active ? ' + isActive);
144
                 self.eventEmitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
144
                 self.eventEmitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
156
 
156
 
157
     dataChannel.onclose = function() {
157
     dataChannel.onclose = function() {
158
         logger.info('The Data Channel closed', dataChannel);
158
         logger.info('The Data Channel closed', dataChannel);
159
-        var idx = self._dataChannels.indexOf(dataChannel);
159
+        const idx = self._dataChannels.indexOf(dataChannel);
160
         if (idx > -1) {
160
         if (idx > -1) {
161
             self._dataChannels = self._dataChannels.splice(idx, 1);
161
             self._dataChannels = self._dataChannels.splice(idx, 1);
162
         }
162
         }
210
 DataChannels.prototype._onXXXEndpointChanged = function(xxx, userResource) {
210
 DataChannels.prototype._onXXXEndpointChanged = function(xxx, userResource) {
211
     // Derive the correct words from xxx such as selected and Selected, pinned
211
     // Derive the correct words from xxx such as selected and Selected, pinned
212
     // and Pinned.
212
     // and Pinned.
213
-    var head = xxx.charAt(0);
214
-    var tail = xxx.substring(1);
215
-    var lower = head.toLowerCase() + tail;
216
-    var upper = head.toUpperCase() + tail;
213
+    const head = xxx.charAt(0);
214
+    const tail = xxx.substring(1);
215
+    const lower = head.toLowerCase() + tail;
216
+    const upper = head.toUpperCase() + tail;
217
     logger.log(
217
     logger.log(
218
             'sending ' + lower
218
             'sending ' + lower
219
                 + ' endpoint changed notification to the bridge: ',
219
                 + ' endpoint changed notification to the bridge: ',
220
             userResource);
220
             userResource);
221
 
221
 
222
-    var jsonObject = {};
222
+    const jsonObject = {};
223
 
223
 
224
     jsonObject.colibriClass = upper + 'EndpointChangedEvent';
224
     jsonObject.colibriClass = upper + 'EndpointChangedEvent';
225
     jsonObject[lower + 'Endpoint']
225
     jsonObject[lower + 'Endpoint']
232
 };
232
 };
233
 
233
 
234
 DataChannels.prototype._some = function(callback, thisArg) {
234
 DataChannels.prototype._some = function(callback, thisArg) {
235
-    var dataChannels = this._dataChannels;
235
+    const dataChannels = this._dataChannels;
236
 
236
 
237
     if (dataChannels && dataChannels.length !== 0) {
237
     if (dataChannels && dataChannels.length !== 0) {
238
         if (thisArg) {
238
         if (thisArg) {

+ 10
- 10
modules/RTC/JitsiLocalTrack.js Visa fil

29
  */
29
  */
30
 function JitsiLocalTrack(stream, track, mediaType, videoType, resolution,
30
 function JitsiLocalTrack(stream, track, mediaType, videoType, resolution,
31
                          deviceId, facingMode) {
31
                          deviceId, facingMode) {
32
-    var self = this;
32
+    const self = this;
33
 
33
 
34
     JitsiTrack.call(this,
34
     JitsiTrack.call(this,
35
         null /* RTC */, stream, track,
35
         null /* RTC */, stream, track,
279
         return Promise.resolve();
279
         return Promise.resolve();
280
     }
280
     }
281
 
281
 
282
-    var promise = Promise.resolve();
283
-    var self = this;
282
+    let promise = Promise.resolve();
283
+    const self = this;
284
 
284
 
285
     // Local track can be used out of conference, so we need to handle that
285
     // Local track can be used out of conference, so we need to handle that
286
     // case and mark that track should start muted or not when added to
286
     // case and mark that track should start muted or not when added to
314
             });
314
             });
315
         } else {
315
         } else {
316
             // This path is only for camera.
316
             // This path is only for camera.
317
-            var streamOptions = {
317
+            const streamOptions = {
318
                 cameraDeviceId: this.getDeviceId(),
318
                 cameraDeviceId: this.getDeviceId(),
319
                 devices: [ MediaType.VIDEO ],
319
                 devices: [ MediaType.VIDEO ],
320
                 facingMode: this.getCameraFacingMode()
320
                 facingMode: this.getCameraFacingMode()
325
 
325
 
326
             promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
326
             promise = RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
327
                 .then(function(streamsInfo) {
327
                 .then(function(streamsInfo) {
328
-                    var mediaType = self.getType();
329
-                    var streamInfo = streamsInfo.find(function(info) {
328
+                    const mediaType = self.getType();
329
+                    const streamInfo = streamsInfo.find(function(info) {
330
                         return info.mediaType === mediaType;
330
                         return info.mediaType === mediaType;
331
                     });
331
                     });
332
 
332
 
445
  * @returns {Promise}
445
  * @returns {Promise}
446
  */
446
  */
447
 JitsiLocalTrack.prototype.dispose = function() {
447
 JitsiLocalTrack.prototype.dispose = function() {
448
-    var self = this;
449
-    var promise = Promise.resolve();
448
+    const self = this;
449
+    let promise = Promise.resolve();
450
 
450
 
451
     if (this.conference) {
451
     if (this.conference) {
452
         promise = this.conference.removeTrack(this);
452
         promise = this.conference.removeTrack(this);
510
     // on "attach" call, but for local track we not always have the conference
510
     // on "attach" call, but for local track we not always have the conference
511
     // before attaching. However this may result in duplicated events if they
511
     // before attaching. However this may result in duplicated events if they
512
     // have been triggered on "attach" already.
512
     // have been triggered on "attach" already.
513
-    for(var i = 0; i < this.containers.length; i++) {
513
+    for(let i = 0; i < this.containers.length; i++) {
514
         this._maybeFireTrackAttached(this.containers[i]);
514
         this._maybeFireTrackAttached(this.containers[i]);
515
     }
515
     }
516
 };
516
 };
586
         // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
586
         // and https://bugzilla.mozilla.org/show_bug.cgi?id=1213517 for Firefox.
587
         // Even if a browser implements getSettings() already, it might still
587
         // Even if a browser implements getSettings() already, it might still
588
         // not return anything for 'facingMode'.
588
         // not return anything for 'facingMode'.
589
-        var trackSettings;
589
+        let trackSettings;
590
 
590
 
591
         try {
591
         try {
592
             trackSettings = this.track.getSettings();
592
             trackSettings = this.track.getSettings();

+ 11
- 11
modules/RTC/JitsiRemoteTrack.js Visa fil

1
 /* global */
1
 /* global */
2
 
2
 
3
-var JitsiTrack = require('./JitsiTrack');
3
+const JitsiTrack = require('./JitsiTrack');
4
 import * as JitsiTrackEvents from '../../JitsiTrackEvents';
4
 import * as JitsiTrackEvents from '../../JitsiTrackEvents';
5
-var logger = require('jitsi-meet-logger').getLogger(__filename);
6
-var RTCBrowserType = require('./RTCBrowserType');
7
-var RTCEvents = require('../../service/RTC/RTCEvents');
8
-var Statistics = require('../statistics/statistics');
5
+const logger = require('jitsi-meet-logger').getLogger(__filename);
6
+const RTCBrowserType = require('./RTCBrowserType');
7
+const RTCEvents = require('../../service/RTC/RTCEvents');
8
+const Statistics = require('../statistics/statistics');
9
 
9
 
10
-var ttfmTrackerAudioAttached = false;
11
-var ttfmTrackerVideoAttached = false;
10
+let ttfmTrackerAudioAttached = false;
11
+let ttfmTrackerVideoAttached = false;
12
 
12
 
13
 /**
13
 /**
14
  * Represents a single media track (either audio or video).
14
  * Represents a single media track (either audio or video).
140
 };
140
 };
141
 
141
 
142
 JitsiRemoteTrack.prototype._playCallback = function() {
142
 JitsiRemoteTrack.prototype._playCallback = function() {
143
-    var type = this.isVideoTrack() ? 'video' : 'audio';
143
+    const type = this.isVideoTrack() ? 'video' : 'audio';
144
 
144
 
145
-    var now = window.performance.now();
145
+    const now = window.performance.now();
146
     console.log('(TIME) Render ' + type + ':\t', now);
146
     console.log('(TIME) Render ' + type + ':\t', now);
147
     this.conference.getConnectionTimes()[type + '.render'] = now;
147
     this.conference.getConnectionTimes()[type + '.render'] = now;
148
 
148
 
149
-    var ttfm = now
149
+    const ttfm = now
150
         - (this.conference.getConnectionTimes()['session.initiate']
150
         - (this.conference.getConnectionTimes()['session.initiate']
151
         - this.conference.getConnectionTimes()['muc.joined'])
151
         - this.conference.getConnectionTimes()['muc.joined'])
152
         - (window.connectionTimes['obtainPermissions.end']
152
         - (window.connectionTimes['obtainPermissions.end']
153
         - window.connectionTimes['obtainPermissions.start']);
153
         - window.connectionTimes['obtainPermissions.start']);
154
     this.conference.getConnectionTimes()[type + '.ttfm'] = ttfm;
154
     this.conference.getConnectionTimes()[type + '.ttfm'] = ttfm;
155
     console.log('(TIME) TTFM ' + type + ':\t', ttfm);
155
     console.log('(TIME) TTFM ' + type + ':\t', ttfm);
156
-    var eventName = type + '.ttfm';
156
+    let eventName = type + '.ttfm';
157
     if(this.hasBeenMuted) {
157
     if(this.hasBeenMuted) {
158
         eventName += '.muted';
158
         eventName += '.muted';
159
     }
159
     }

+ 8
- 8
modules/RTC/JitsiTrack.js Visa fil

11
 /**
11
 /**
12
  * Maps our handler types to MediaStreamTrack properties.
12
  * Maps our handler types to MediaStreamTrack properties.
13
  */
13
  */
14
-var trackHandler2Prop = {
14
+const trackHandler2Prop = {
15
     'track_mute': 'onmute',// Not supported on FF
15
     'track_mute': 'onmute',// Not supported on FF
16
     'track_unmute': 'onunmute',
16
     'track_unmute': 'onunmute',
17
     'track_ended': 'onended'
17
     'track_ended': 'onended'
24
  * to which 'onended' handling will be added.
24
  * to which 'onended' handling will be added.
25
  */
25
  */
26
 function implementOnEndedHandling(jitsiTrack) {
26
 function implementOnEndedHandling(jitsiTrack) {
27
-    var stream = jitsiTrack.getOriginalStream();
27
+    const stream = jitsiTrack.getOriginalStream();
28
 
28
 
29
     if(!stream) {
29
     if(!stream) {
30
         return;
30
         return;
31
     }
31
     }
32
 
32
 
33
-    var originalStop = stream.stop;
33
+    const originalStop = stream.stop;
34
     stream.stop = function() {
34
     stream.stop = function() {
35
         originalStop.apply(stream);
35
         originalStop.apply(stream);
36
         if (jitsiTrack.isActive()) {
36
         if (jitsiTrack.isActive()) {
265
  * JitsiTrack is currently attached.
265
  * JitsiTrack is currently attached.
266
  */
266
  */
267
 JitsiTrack.prototype.detach = function(container) {
267
 JitsiTrack.prototype.detach = function(container) {
268
-    for (var cs = this.containers, i = cs.length - 1; i >= 0; --i) {
269
-        var c = cs[i];
268
+    for (let cs = this.containers, i = cs.length - 1; i >= 0; --i) {
269
+        const c = cs[i];
270
         if (!container) {
270
         if (!container) {
271
             RTCUtils.attachMediaStream(c, null);
271
             RTCUtils.attachMediaStream(c, null);
272
         }
272
         }
382
  * no stream is attached.
382
  * no stream is attached.
383
  */
383
  */
384
 JitsiTrack.prototype.getMSID = function() {
384
 JitsiTrack.prototype.getMSID = function() {
385
-    var streamId = this.getStreamId();
386
-    var trackId = this.getTrackId();
385
+    const streamId = this.getStreamId();
386
+    const trackId = this.getTrackId();
387
     return streamId && trackId ? streamId + ' ' + trackId : null;
387
     return streamId && trackId ? streamId + ' ' + trackId : null;
388
 };
388
 };
389
 
389
 
396
  * @returns {Promise}
396
  * @returns {Promise}
397
  */
397
  */
398
 JitsiTrack.prototype.setAudioOutput = function(audioOutputDeviceId) {
398
 JitsiTrack.prototype.setAudioOutput = function(audioOutputDeviceId) {
399
-    var self = this;
399
+    const self = this;
400
 
400
 
401
     if (!RTCUtils.isDeviceChangeAvailable('output')) {
401
     if (!RTCUtils.isDeviceChangeAvailable('output')) {
402
         return Promise.reject(
402
         return Promise.reject(

+ 7
- 7
modules/RTC/RTC.js Visa fil

16
 const logger = getLogger(__filename);
16
 const logger = getLogger(__filename);
17
 
17
 
18
 function createLocalTracks(tracksInfo, options) {
18
 function createLocalTracks(tracksInfo, options) {
19
-    var newTracks = [];
20
-    var deviceId = null;
19
+    const newTracks = [];
20
+    let deviceId = null;
21
     tracksInfo.forEach(function(trackInfo) {
21
     tracksInfo.forEach(function(trackInfo) {
22
         if (trackInfo.mediaType === MediaType.AUDIO) {
22
         if (trackInfo.mediaType === MediaType.AUDIO) {
23
             deviceId = options.micDeviceId;
23
             deviceId = options.micDeviceId;
24
         } else if (trackInfo.videoType === VideoType.CAMERA) {
24
         } else if (trackInfo.videoType === VideoType.CAMERA) {
25
             deviceId = options.cameraDeviceId;
25
             deviceId = options.cameraDeviceId;
26
         }
26
         }
27
-        var localTrack
27
+        const localTrack
28
             = new JitsiLocalTrack(
28
             = new JitsiLocalTrack(
29
                 trackInfo.stream,
29
                 trackInfo.stream,
30
                 trackInfo.track,
30
                 trackInfo.track,
94
     static obtainAudioAndVideoPermissions(options) {
94
     static obtainAudioAndVideoPermissions(options) {
95
         return RTCUtils.obtainAudioAndVideoPermissions(options).then(
95
         return RTCUtils.obtainAudioAndVideoPermissions(options).then(
96
             function(tracksInfo) {
96
             function(tracksInfo) {
97
-                var tracks = createLocalTracks(tracksInfo, options);
97
+                const tracks = createLocalTracks(tracksInfo, options);
98
                 return !tracks.some(track =>
98
                 return !tracks.some(track =>
99
                     !track._isReceivingData()) ? tracks
99
                     !track._isReceivingData()) ? tracks
100
                         : Promise.reject(new JitsiTrackError(
100
                         : Promise.reject(new JitsiTrackError(
638
         if(!resource) {
638
         if(!resource) {
639
             return;
639
             return;
640
         }
640
         }
641
-        var audioTrack = this.getRemoteAudioTrack(resource);
641
+        const audioTrack = this.getRemoteAudioTrack(resource);
642
         if(audioTrack) {
642
         if(audioTrack) {
643
             audioTrack.setAudioLevel(audioLevel);
643
             audioTrack.setAudioLevel(audioLevel);
644
         }
644
         }
679
      * @param from {string} user id
679
      * @param from {string} user id
680
      */
680
      */
681
     handleRemoteTrackMute(type, isMuted, from) {
681
     handleRemoteTrackMute(type, isMuted, from) {
682
-        var track = this.getRemoteTrackByType(type, from);
682
+        const track = this.getRemoteTrackByType(type, from);
683
         if (track) {
683
         if (track) {
684
             track.setMute(isMuted);
684
             track.setMute(isMuted);
685
         }
685
         }
691
      * @param from {string} user id
691
      * @param from {string} user id
692
      */
692
      */
693
     handleRemoteTrackVideoTypeChanged(value, from) {
693
     handleRemoteTrackVideoTypeChanged(value, from) {
694
-        var videoTrack = this.getRemoteVideoTrack(from);
694
+        const videoTrack = this.getRemoteVideoTrack(from);
695
         if (videoTrack) {
695
         if (videoTrack) {
696
             videoTrack._setVideoType(value);
696
             videoTrack._setVideoType(value);
697
         }
697
         }

+ 27
- 31
modules/RTC/RTCBrowserType.js Visa fil

1
-var logger = require('jitsi-meet-logger').getLogger(__filename);
1
+const logger = require('jitsi-meet-logger').getLogger(__filename);
2
 
2
 
3
-var currentBrowser;
3
+let currentBrowser;
4
 
4
 
5
-var browserVersion;
6
-
7
-var isAndroid;
8
-
9
-var RTCBrowserType = {
5
+const RTCBrowserType = {
10
 
6
 
11
     RTC_BROWSER_CHROME: 'rtc_browser.chrome',
7
     RTC_BROWSER_CHROME: 'rtc_browser.chrome',
12
 
8
 
37
      * @returns {string}
33
      * @returns {string}
38
      */
34
      */
39
     getBrowserName() {
35
     getBrowserName() {
40
-        var browser;
36
+        let browser;
41
         if (RTCBrowserType.isAndroid()) {
37
         if (RTCBrowserType.isAndroid()) {
42
             browser = 'android';
38
             browser = 'android';
43
         } else {
39
         } else {
199
 function detectChrome() {
195
 function detectChrome() {
200
     if (navigator.webkitGetUserMedia) {
196
     if (navigator.webkitGetUserMedia) {
201
         currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
197
         currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
202
-        var userAgent = navigator.userAgent.toLowerCase();
198
+        const userAgent = navigator.userAgent.toLowerCase();
203
         // We can assume that user agent is chrome, because it's
199
         // We can assume that user agent is chrome, because it's
204
         // enforced when 'ext' streaming method is set
200
         // enforced when 'ext' streaming method is set
205
-        var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
201
+        const ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
206
         logger.log('This appears to be Chrome, ver: ' + ver);
202
         logger.log('This appears to be Chrome, ver: ' + ver);
207
         return ver;
203
         return ver;
208
     }
204
     }
210
 }
206
 }
211
 
207
 
212
 function detectOpera() {
208
 function detectOpera() {
213
-    var userAgent = navigator.userAgent;
209
+    const userAgent = navigator.userAgent;
214
     if (userAgent.match(/Opera|OPR/)) {
210
     if (userAgent.match(/Opera|OPR/)) {
215
         currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
211
         currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
216
-        var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
212
+        const version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
217
         logger.info('This appears to be Opera, ver: ' + version);
213
         logger.info('This appears to be Opera, ver: ' + version);
218
         return version;
214
         return version;
219
     }
215
     }
223
 function detectFirefox() {
219
 function detectFirefox() {
224
     if (navigator.mozGetUserMedia) {
220
     if (navigator.mozGetUserMedia) {
225
         currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
221
         currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
226
-        var version = parseInt(
222
+        const version = parseInt(
227
             navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
223
             navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
228
         logger.log('This appears to be Firefox, ver: ' + version);
224
         logger.log('This appears to be Firefox, ver: ' + version);
229
         return version;
225
         return version;
242
 }
238
 }
243
 
239
 
244
 function detectIE() {
240
 function detectIE() {
245
-    var version;
246
-    var ua = window.navigator.userAgent;
241
+    let version;
242
+    const ua = window.navigator.userAgent;
247
 
243
 
248
-    var msie = ua.indexOf('MSIE ');
244
+    const msie = ua.indexOf('MSIE ');
249
     if (msie > 0) {
245
     if (msie > 0) {
250
         // IE 10 or older => return version number
246
         // IE 10 or older => return version number
251
         version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
247
         version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
252
     }
248
     }
253
 
249
 
254
-    var trident = ua.indexOf('Trident/');
250
+    const trident = ua.indexOf('Trident/');
255
     if (!version && trident > 0) {
251
     if (!version && trident > 0) {
256
         // IE 11 => return version number
252
         // IE 11 => return version number
257
-        var rv = ua.indexOf('rv:');
253
+        const rv = ua.indexOf('rv:');
258
         version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
254
         version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
259
     }
255
     }
260
 
256
 
261
-    var edge = ua.indexOf('Edge/');
257
+    const edge = ua.indexOf('Edge/');
262
     if (!version && edge > 0) {
258
     if (!version && edge > 0) {
263
         // IE 12 => return version number
259
         // IE 12 => return version number
264
         version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
260
         version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
275
  * Detects Electron environment.
271
  * Detects Electron environment.
276
  */
272
  */
277
 function detectElectron() {
273
 function detectElectron() {
278
-    var userAgent = navigator.userAgent;
274
+    const userAgent = navigator.userAgent;
279
     if (userAgent.match(/Electron/)) {
275
     if (userAgent.match(/Electron/)) {
280
         currentBrowser = RTCBrowserType.RTC_BROWSER_ELECTRON;
276
         currentBrowser = RTCBrowserType.RTC_BROWSER_ELECTRON;
281
-        var version = userAgent.match(/Electron\/([\d.]+)/)[1];
277
+        const version = userAgent.match(/Electron\/([\d.]+)/)[1];
282
         logger.info('This appears to be Electron, ver: ' + version);
278
         logger.info('This appears to be Electron, ver: ' + version);
283
         return version;
279
         return version;
284
     }
280
     }
286
 }
282
 }
287
 
283
 
288
 function detectNWJS() {
284
 function detectNWJS() {
289
-    var userAgent = navigator.userAgent;
285
+    const userAgent = navigator.userAgent;
290
     if (userAgent.match(/JitsiMeetNW/)) {
286
     if (userAgent.match(/JitsiMeetNW/)) {
291
         currentBrowser = RTCBrowserType.RTC_BROWSER_NWJS;
287
         currentBrowser = RTCBrowserType.RTC_BROWSER_NWJS;
292
-        var version = userAgent.match(/JitsiMeetNW\/([\d.]+)/)[1];
288
+        const version = userAgent.match(/JitsiMeetNW\/([\d.]+)/)[1];
293
         logger.info('This appears to be JitsiMeetNW, ver: ' + version);
289
         logger.info('This appears to be JitsiMeetNW, ver: ' + version);
294
         return version;
290
         return version;
295
     }
291
     }
297
 }
293
 }
298
 
294
 
299
 function detectReactNative() {
295
 function detectReactNative() {
300
-    var match
296
+    const match
301
         = navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);
297
         = navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);
302
-    var version;
298
+    let version;
303
     // If we're remote debugging a React Native app, it may be treated as
299
     // If we're remote debugging a React Native app, it may be treated as
304
     // Chrome. Check navigator.product as well and always return some version
300
     // Chrome. Check navigator.product as well and always return some version
305
     // even if we can't get the real one.
301
     // even if we can't get the real one.
306
     if (match || navigator.product === 'ReactNative') {
302
     if (match || navigator.product === 'ReactNative') {
307
         currentBrowser = RTCBrowserType.RTC_BROWSER_REACT_NATIVE;
303
         currentBrowser = RTCBrowserType.RTC_BROWSER_REACT_NATIVE;
308
-        var name;
304
+        let name;
309
         if (match && match.length > 2) {
305
         if (match && match.length > 2) {
310
             name = match[1];
306
             name = match[1];
311
             version = match[2];
307
             version = match[2];
321
 }
317
 }
322
 
318
 
323
 function detectBrowser() {
319
 function detectBrowser() {
324
-    var version;
325
-    var detectors = [
320
+    let version;
321
+    const detectors = [
326
         detectReactNative,
322
         detectReactNative,
327
         detectElectron,
323
         detectElectron,
328
         detectNWJS,
324
         detectNWJS,
333
         detectSafari
329
         detectSafari
334
     ];
330
     ];
335
     // Try all browser detectors
331
     // Try all browser detectors
336
-    for (var i = 0; i < detectors.length; i++) {
332
+    for (let i = 0; i < detectors.length; i++) {
337
         version = detectors[i]();
333
         version = detectors[i]();
338
         if (version) {
334
         if (version) {
339
             return version;
335
             return version;
344
     return 1;
340
     return 1;
345
 }
341
 }
346
 
342
 
347
-browserVersion = detectBrowser();
348
-isAndroid = navigator.userAgent.indexOf('Android') != -1;
343
+const browserVersion = detectBrowser();
344
+const isAndroid = navigator.userAgent.indexOf('Android') != -1;
349
 
345
 
350
 module.exports = RTCBrowserType;
346
 module.exports = RTCBrowserType;

+ 5
- 5
modules/RTC/RTCUIHelper.js Visa fil

1
 /* global $ */
1
 /* global $ */
2
 
2
 
3
-var logger = require('jitsi-meet-logger').getLogger(__filename);
4
-var RTCBrowserType = require('./RTCBrowserType');
3
+const logger = require('jitsi-meet-logger').getLogger(__filename);
4
+const RTCBrowserType = require('./RTCBrowserType');
5
 
5
 
6
-var RTCUIHelper = {
6
+const RTCUIHelper = {
7
 
7
 
8
     /**
8
     /**
9
      * Returns the name of 'video' element depending on the browser that we're
9
      * Returns the name of 'video' element depending on the browser that we're
22
      *          container or undefined otherwise.
22
      *          container or undefined otherwise.
23
      */
23
      */
24
     findVideoElement(containerElement) {
24
     findVideoElement(containerElement) {
25
-        var videoElemName = RTCUIHelper.getVideoElementName();
25
+        const videoElemName = RTCUIHelper.getVideoElementName();
26
         if (!RTCBrowserType.isTemasysPluginUsed()) {
26
         if (!RTCBrowserType.isTemasysPluginUsed()) {
27
             return $(containerElement).find(videoElemName)[0];
27
             return $(containerElement).find(videoElemName)[0];
28
         }
28
         }
29
-        var matching = $(containerElement).find(
29
+        const matching = $(containerElement).find(
30
                 ' ' + videoElemName + '>param[value="video"]');
30
                 ' ' + videoElemName + '>param[value="video"]');
31
         if (matching.length) {
31
         if (matching.length) {
32
             if (matching.length > 1) {
32
             if (matching.length > 1) {

+ 57
- 56
modules/RTC/RTCUtils.js Visa fil

35
         ? require('./adapter.screenshare')
35
         ? require('./adapter.screenshare')
36
         : undefined;
36
         : undefined;
37
 
37
 
38
-var eventEmitter = new EventEmitter();
38
+const eventEmitter = new EventEmitter();
39
 
39
 
40
-var AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
40
+const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
41
 
41
 
42
-var devices = {
42
+const devices = {
43
     audio: false,
43
     audio: false,
44
     video: false
44
     video: false
45
 };
45
 };
46
 
46
 
47
 // Currently audio output device change is supported only in Chrome and
47
 // Currently audio output device change is supported only in Chrome and
48
 // default output always has 'default' device ID
48
 // default output always has 'default' device ID
49
-var audioOutputDeviceId = 'default'; // default device
49
+let audioOutputDeviceId = 'default'; // default device
50
 // whether user has explicitly set a device to use
50
 // whether user has explicitly set a device to use
51
-var audioOutputChanged = false;
51
+let audioOutputChanged = false;
52
 // Disables Acoustic Echo Cancellation
52
 // Disables Acoustic Echo Cancellation
53
-var disableAEC = false;
53
+let disableAEC = false;
54
 // Disables Noise Suppression
54
 // Disables Noise Suppression
55
-var disableNS = false;
55
+let disableNS = false;
56
 
56
 
57
-var featureDetectionAudioEl = document.createElement('audio');
58
-var isAudioOutputDeviceChangeAvailable
57
+const featureDetectionAudioEl = document.createElement('audio');
58
+const isAudioOutputDeviceChangeAvailable
59
     = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
59
     = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
60
 
60
 
61
-var currentlyAvailableMediaDevices;
61
+let currentlyAvailableMediaDevices;
62
 
62
 
63
-var rawEnumerateDevicesWithCallback = undefined;
63
+let rawEnumerateDevicesWithCallback = undefined;
64
 /**
64
 /**
65
  * "rawEnumerateDevicesWithCallback" will be initialized only after WebRTC is
65
  * "rawEnumerateDevicesWithCallback" will be initialized only after WebRTC is
66
  * ready. Otherwise it is too early to assume that the devices listing is not
66
  * ready. Otherwise it is too early to assume that the devices listing is not
97
 // 'devicechange' event can be found in spec -
97
 // 'devicechange' event can be found in spec -
98
 // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
98
 // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
99
 // TODO: check MS Edge
99
 // TODO: check MS Edge
100
-var isDeviceChangeEventSupported = false;
100
+const isDeviceChangeEventSupported = false;
101
 
101
 
102
-var rtcReady = false;
102
+let rtcReady = false;
103
 
103
 
104
 function setResolutionConstraints(constraints, resolution) {
104
 function setResolutionConstraints(constraints, resolution) {
105
-    var isAndroid = RTCBrowserType.isAndroid();
105
+    const isAndroid = RTCBrowserType.isAndroid();
106
 
106
 
107
     if (Resolutions[resolution]) {
107
     if (Resolutions[resolution]) {
108
         constraints.video.mandatory.minWidth = Resolutions[resolution].width;
108
         constraints.video.mandatory.minWidth = Resolutions[resolution].width;
139
  * @param {bool} firefox_fake_device
139
  * @param {bool} firefox_fake_device
140
  */
140
  */
141
 function getConstraints(um, options) {
141
 function getConstraints(um, options) {
142
-    var constraints = {audio: false, video: false};
142
+    const constraints = {audio: false, video: false};
143
 
143
 
144
     // Don't mix new and old style settings for Chromium as this leads
144
     // Don't mix new and old style settings for Chromium as this leads
145
     // to TypeError in new Chromium versions. @see
145
     // to TypeError in new Chromium versions. @see
148
     // new style constraints when new versions of Chromium and Firefox will
148
     // new style constraints when new versions of Chromium and Firefox will
149
     // have stable support of new constraints format. For more information
149
     // have stable support of new constraints format. For more information
150
     // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
150
     // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
151
-    var isNewStyleConstraintsSupported
151
+    const isNewStyleConstraintsSupported
152
         = RTCBrowserType.isFirefox()
152
         = RTCBrowserType.isFirefox()
153
         || RTCBrowserType.isReactNative()
153
         || RTCBrowserType.isReactNative()
154
         || RTCBrowserType.isTemasysPluginUsed();
154
         || RTCBrowserType.isTemasysPluginUsed();
172
             // TODO: Maybe use "exact" syntax if options.facingMode is defined,
172
             // TODO: Maybe use "exact" syntax if options.facingMode is defined,
173
             // but this probably needs to be decided when updating other
173
             // but this probably needs to be decided when updating other
174
             // constraints, as we currently don't use "exact" syntax anywhere.
174
             // constraints, as we currently don't use "exact" syntax anywhere.
175
-            var facingMode = options.facingMode || CameraFacingMode.USER;
175
+            const facingMode = options.facingMode || CameraFacingMode.USER;
176
 
176
 
177
             if (isNewStyleConstraintsSupported) {
177
             if (isNewStyleConstraintsSupported) {
178
                 constraints.video.facingMode = facingMode;
178
                 constraints.video.facingMode = facingMode;
263
             };
263
             };
264
 
264
 
265
         } else {
265
         } else {
266
-            var errmsg
266
+            const errmsg
267
                 = '\'screen\' WebRTC media source is supported only in Chrome'
267
                 = '\'screen\' WebRTC media source is supported only in Chrome'
268
                     + ' and with Temasys plugin';
268
                     + ' and with Temasys plugin';
269
             GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
269
             GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
311
  * @param stream the stream we received from calling getUserMedia.
311
  * @param stream the stream we received from calling getUserMedia.
312
  */
312
  */
313
 function setAvailableDevices(um, stream) {
313
 function setAvailableDevices(um, stream) {
314
-    var audioTracksReceived = stream && !!stream.getAudioTracks().length;
315
-    var videoTracksReceived = stream && !!stream.getVideoTracks().length;
314
+    const audioTracksReceived = stream && !!stream.getAudioTracks().length;
315
+    const videoTracksReceived = stream && !!stream.getVideoTracks().length;
316
 
316
 
317
     if (um.indexOf('video') != -1) {
317
     if (um.indexOf('video') != -1) {
318
         devices.video = videoTracksReceived;
318
         devices.video = videoTracksReceived;
448
     fn && fn(...args);
448
     fn && fn(...args);
449
 }
449
 }
450
 
450
 
451
-var getUserMediaStatus = {
451
+const getUserMediaStatus = {
452
     initialized: false,
452
     initialized: false,
453
     callbacks: []
453
     callbacks: []
454
 };
454
 };
522
  * @param {Object} source
522
  * @param {Object} source
523
  */
523
  */
524
 function convertMediaStreamTrackSource(source) {
524
 function convertMediaStreamTrackSource(source) {
525
-    var kind = (source.kind || '').toLowerCase();
525
+    const kind = (source.kind || '').toLowerCase();
526
 
526
 
527
     return {
527
     return {
528
         facing: source.facing || null,
528
         facing: source.facing || null,
543
         return options.successCallback(options.streams || {});
543
         return options.successCallback(options.streams || {});
544
     }
544
     }
545
 
545
 
546
-    var device = options.devices.splice(0, 1);
547
-    var devices = [];
546
+    const device = options.devices.splice(0, 1);
547
+    const devices = [];
548
     devices.push(device);
548
     devices.push(device);
549
     options.deviceGUM[device](function(stream) {
549
     options.deviceGUM[device](function(stream) {
550
         options.streams = options.streams || {};
550
         options.streams = options.streams || {};
570
  * @returns {*[]} object that describes the new streams
570
  * @returns {*[]} object that describes the new streams
571
  */
571
  */
572
 function handleLocalStream(streams, resolution) {
572
 function handleLocalStream(streams, resolution) {
573
-    var audioStream, desktopStream, res = [], videoStream;
573
+    let audioStream, desktopStream, videoStream;
574
+    const res = [];
574
 
575
 
575
     // XXX The function obtainAudioAndVideoPermissions has examined the type of
576
     // XXX The function obtainAudioAndVideoPermissions has examined the type of
576
     // the browser, its capabilities, etc. and has taken the decision whether to
577
     // the browser, its capabilities, etc. and has taken the decision whether to
582
         // As mentioned above, certian types of browser (e.g. Chrome) support
583
         // As mentioned above, certian types of browser (e.g. Chrome) support
583
         // (with a result which meets our requirements expressed bellow) calling
584
         // (with a result which meets our requirements expressed bellow) calling
584
         // getUserMedia once for both audio and video.
585
         // getUserMedia once for both audio and video.
585
-        var audioVideo = streams.audioVideo;
586
+        const audioVideo = streams.audioVideo;
586
         if (audioVideo) {
587
         if (audioVideo) {
587
-            var audioTracks = audioVideo.getAudioTracks();
588
+            const audioTracks = audioVideo.getAudioTracks();
588
             if (audioTracks.length) {
589
             if (audioTracks.length) {
589
                 // eslint-disable-next-line new-cap
590
                 // eslint-disable-next-line new-cap
590
                 audioStream = new webkitMediaStream();
591
                 audioStream = new webkitMediaStream();
591
-                for (var i = 0; i < audioTracks.length; i++) {
592
+                for (let i = 0; i < audioTracks.length; i++) {
592
                     audioStream.addTrack(audioTracks[i]);
593
                     audioStream.addTrack(audioTracks[i]);
593
                 }
594
                 }
594
             }
595
             }
595
 
596
 
596
-            var videoTracks = audioVideo.getVideoTracks();
597
+            const videoTracks = audioVideo.getVideoTracks();
597
             if (videoTracks.length) {
598
             if (videoTracks.length) {
598
                 // eslint-disable-next-line new-cap
599
                 // eslint-disable-next-line new-cap
599
                 videoStream = new webkitMediaStream();
600
                 videoStream = new webkitMediaStream();
600
-                for (var j = 0; j < videoTracks.length; j++) {
601
+                for (let j = 0; j < videoTracks.length; j++) {
601
                     videoStream.addTrack(videoTracks[j]);
602
                     videoStream.addTrack(videoTracks[j]);
602
                 }
603
                 }
603
             }
604
             }
649
  */
650
  */
650
 function wrapAttachMediaStream(origAttachMediaStream) {
651
 function wrapAttachMediaStream(origAttachMediaStream) {
651
     return function(element, stream) {
652
     return function(element, stream) {
652
-        var res = origAttachMediaStream.apply(rtcUtils, arguments);
653
+        const res = origAttachMediaStream.apply(rtcUtils, arguments);
653
 
654
 
654
         if (stream
655
         if (stream
655
                 && rtcUtils.isDeviceChangeAvailable('output')
656
                 && rtcUtils.isDeviceChangeAvailable('output')
659
                 && audioOutputChanged) {
660
                 && audioOutputChanged) {
660
             element.setSinkId(rtcUtils.getAudioOutputDevice())
661
             element.setSinkId(rtcUtils.getAudioOutputDevice())
661
                 .catch(function(ex) {
662
                 .catch(function(ex) {
662
-                    var err = new JitsiTrackError(ex, null, ['audiooutput']);
663
+                    const err = new JitsiTrackError(ex, null, ['audiooutput']);
663
 
664
 
664
                     GlobalOnErrorHandler.callUnhandledRejectionHandler(
665
                     GlobalOnErrorHandler.callUnhandledRejectionHandler(
665
                         {promise: this, reason: err});
666
                         {promise: this, reason: err});
696
  */
697
  */
697
 function defaultSetVideoSrc(element, stream) {
698
 function defaultSetVideoSrc(element, stream) {
698
     // srcObject
699
     // srcObject
699
-    var srcObjectPropertyName = 'srcObject';
700
+    let srcObjectPropertyName = 'srcObject';
700
     if (!(srcObjectPropertyName in element)) {
701
     if (!(srcObjectPropertyName in element)) {
701
         srcObjectPropertyName = 'mozSrcObject';
702
         srcObjectPropertyName = 'mozSrcObject';
702
         if (!(srcObjectPropertyName in element)) {
703
         if (!(srcObjectPropertyName in element)) {
709
     }
710
     }
710
 
711
 
711
     // src
712
     // src
712
-    var src;
713
+    let src;
713
     if (stream) {
714
     if (stream) {
714
         src = stream.jitsiObjectURL;
715
         src = stream.jitsiObjectURL;
715
         // Save the created URL for stream so we can reuse it and not keep
716
         // Save the created URL for stream so we can reuse it and not keep
741
 
742
 
742
         return new Promise(function(resolve, reject) {
743
         return new Promise(function(resolve, reject) {
743
             if (RTCBrowserType.isFirefox()) {
744
             if (RTCBrowserType.isFirefox()) {
744
-                var FFversion = RTCBrowserType.getFirefoxVersion();
745
+                const FFversion = RTCBrowserType.getFirefoxVersion();
745
                 if (FFversion < 40) {
746
                 if (FFversion < 40) {
746
                     rejectWithWebRTCNotSupported(
747
                     rejectWithWebRTCNotSupported(
747
                         `Firefox version too old: ${FFversion}.`
748
                         `Firefox version too old: ${FFversion}.`
773
                     return element;
774
                     return element;
774
                 });
775
                 });
775
                 this.getStreamID = function(stream) {
776
                 this.getStreamID = function(stream) {
776
-                    var id = stream.id;
777
+                    let id = stream.id;
777
                     if (!id) {
778
                     if (!id) {
778
-                        var tracks = stream.getVideoTracks();
779
+                        let tracks = stream.getVideoTracks();
779
                         if (!tracks || tracks.length === 0) {
780
                         if (!tracks || tracks.length === 0) {
780
                             tracks = stream.getAudioTracks();
781
                             tracks = stream.getAudioTracks();
781
                         }
782
                         }
792
                     || RTCBrowserType.isReactNative()) {
793
                     || RTCBrowserType.isReactNative()) {
793
 
794
 
794
                 this.peerconnection = webkitRTCPeerConnection;
795
                 this.peerconnection = webkitRTCPeerConnection;
795
-                var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
796
+                const getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
796
                 if (navigator.mediaDevices) {
797
                 if (navigator.mediaDevices) {
797
                     this.getUserMedia = wrapGetUserMedia(getUserMedia);
798
                     this.getUserMedia = wrapGetUserMedia(getUserMedia);
798
                     this.enumerateDevices = wrapEnumerateDevices(
799
                     this.enumerateDevices = wrapEnumerateDevices(
813
                     // React Native at the time of this writing returns a number
814
                     // React Native at the time of this writing returns a number
814
                     // for the id of MediaStream. Let's just say that a number
815
                     // for the id of MediaStream. Let's just say that a number
815
                     // contains no special characters.
816
                     // contains no special characters.
816
-                    var id = stream.id;
817
+                    const id = stream.id;
817
                     // XXX The return statement is affected by automatic
818
                     // XXX The return statement is affected by automatic
818
                     // semicolon insertion (ASI). No line terminator is allowed
819
                     // semicolon insertion (ASI). No line terminator is allowed
819
                     // between the return keyword and the expression.
820
                     // between the return keyword and the expression.
862
 
863
 
863
                             // The container must be visible in order to play or
864
                             // The container must be visible in order to play or
864
                             // attach the stream when Temasys plugin is in use
865
                             // attach the stream when Temasys plugin is in use
865
-                            var containerSel = $(element);
866
+                            const containerSel = $(element);
866
                             if (RTCBrowserType.isTemasysPluginUsed()
867
                             if (RTCBrowserType.isTemasysPluginUsed()
867
                                     && !containerSel.is(':visible')) {
868
                                     && !containerSel.is(':visible')) {
868
                                 containerSel.show();
869
                                 containerSel.show();
869
                             }
870
                             }
870
-                            var video = !!stream.getVideoTracks().length;
871
+                            const video = !!stream.getVideoTracks().length;
871
                             if (video && !$(element).is(':visible')) {
872
                             if (video && !$(element).is(':visible')) {
872
                                 throw new Error(
873
                                 throw new Error(
873
                                     'video element must be visible to attach'
874
                                     'video element must be visible to attach'
938
     **/
939
     **/
939
     getUserMediaWithConstraints(um, success_callback, failure_callback, options) {
940
     getUserMediaWithConstraints(um, success_callback, failure_callback, options) {
940
         options = options || {};
941
         options = options || {};
941
-        var constraints = getConstraints(um, options);
942
+        const constraints = getConstraints(um, options);
942
 
943
 
943
         logger.info('Get media constraints', constraints);
944
         logger.info('Get media constraints', constraints);
944
 
945
 
981
      * @returns {*} Promise object that will receive the new JitsiTracks
982
      * @returns {*} Promise object that will receive the new JitsiTracks
982
      */
983
      */
983
     obtainAudioAndVideoPermissions(options) {
984
     obtainAudioAndVideoPermissions(options) {
984
-        var self = this;
985
+        const self = this;
985
 
986
 
986
         options = options || {};
987
         options = options || {};
987
-        var dsOptions = options.desktopSharingExtensionExternalInstallation;
988
+        const dsOptions = options.desktopSharingExtensionExternalInstallation;
988
         return new Promise(function(resolve, reject) {
989
         return new Promise(function(resolve, reject) {
989
-            var successCallback = function(stream) {
990
+            const successCallback = function(stream) {
990
                 resolve(handleLocalStream(stream, options.resolution));
991
                 resolve(handleLocalStream(stream, options.resolution));
991
             };
992
             };
992
 
993
 
1004
                     // NSNumber as) a MediaStream ID.
1005
                     // NSNumber as) a MediaStream ID.
1005
                     || RTCBrowserType.isReactNative()
1006
                     || RTCBrowserType.isReactNative()
1006
                     || RTCBrowserType.isTemasysPluginUsed()) {
1007
                     || RTCBrowserType.isTemasysPluginUsed()) {
1007
-                var GUM = function(device, s, e) {
1008
+                const GUM = function(device, s, e) {
1008
                     this.getUserMediaWithConstraints(device, s, e, options);
1009
                     this.getUserMediaWithConstraints(device, s, e, options);
1009
                 };
1010
                 };
1010
 
1011
 
1011
-                var deviceGUM = {
1012
+                const deviceGUM = {
1012
                     'audio': GUM.bind(self, ['audio']),
1013
                     'audio': GUM.bind(self, ['audio']),
1013
                     'video': GUM.bind(self, ['video'])
1014
                     'video': GUM.bind(self, ['video'])
1014
                 };
1015
                 };
1034
                     deviceGUM
1035
                     deviceGUM
1035
                 });
1036
                 });
1036
             } else {
1037
             } else {
1037
-                var hasDesktop = options.devices.indexOf('desktop') > -1;
1038
+                const hasDesktop = options.devices.indexOf('desktop') > -1;
1038
                 if (hasDesktop) {
1039
                 if (hasDesktop) {
1039
                     options.devices.splice(options.devices.indexOf('desktop'), 1);
1040
                     options.devices.splice(options.devices.indexOf('desktop'), 1);
1040
                 }
1041
                 }
1043
                     this.getUserMediaWithConstraints(
1044
                     this.getUserMediaWithConstraints(
1044
                         options.devices,
1045
                         options.devices,
1045
                         function(stream) {
1046
                         function(stream) {
1046
-                            var audioDeviceRequested = options.devices.indexOf('audio') !== -1;
1047
-                            var videoDeviceRequested = options.devices.indexOf('video') !== -1;
1048
-                            var audioTracksReceived = !!stream.getAudioTracks().length;
1049
-                            var videoTracksReceived = !!stream.getVideoTracks().length;
1047
+                            const audioDeviceRequested = options.devices.indexOf('audio') !== -1;
1048
+                            const videoDeviceRequested = options.devices.indexOf('video') !== -1;
1049
+                            const audioTracksReceived = !!stream.getAudioTracks().length;
1050
+                            const videoTracksReceived = !!stream.getVideoTracks().length;
1050
 
1051
 
1051
                             if((audioDeviceRequested && !audioTracksReceived)
1052
                             if((audioDeviceRequested && !audioTracksReceived)
1052
                                 || (videoDeviceRequested && !videoTracksReceived)) {
1053
                                 || (videoDeviceRequested && !videoTracksReceived)) {
1057
                                 // didn't get corresponding MediaStreamTrack in
1058
                                 // didn't get corresponding MediaStreamTrack in
1058
                                 // response stream. We don't know the reason why
1059
                                 // response stream. We don't know the reason why
1059
                                 // this happened, so reject with general error.
1060
                                 // this happened, so reject with general error.
1060
-                                var devices = [];
1061
+                                const devices = [];
1061
 
1062
 
1062
                                 if (audioDeviceRequested && !audioTracksReceived) {
1063
                                 if (audioDeviceRequested && !audioTracksReceived) {
1063
                                     devices.push('audio');
1064
                                     devices.push('audio');
1227
         }
1228
         }
1228
 
1229
 
1229
         // if we have done createObjectURL, lets clean it
1230
         // if we have done createObjectURL, lets clean it
1230
-        var url = mediaStream.jitsiObjectURL;
1231
+        const url = mediaStream.jitsiObjectURL;
1231
         if (url) {
1232
         if (url) {
1232
             delete mediaStream.jitsiObjectURL;
1233
             delete mediaStream.jitsiObjectURL;
1233
             (URL || webkitURL).revokeObjectURL(url);
1234
             (URL || webkitURL).revokeObjectURL(url);
1291
      * @returns {MediaDeviceInfo} device.
1292
      * @returns {MediaDeviceInfo} device.
1292
      */
1293
      */
1293
     getEventDataForActiveDevice(device) {
1294
     getEventDataForActiveDevice(device) {
1294
-        var devices = [];
1295
-        var deviceData = {
1295
+        const devices = [];
1296
+        const deviceData = {
1296
             'deviceId': device.deviceId,
1297
             'deviceId': device.deviceId,
1297
             'kind':     device.kind,
1298
             'kind':     device.kind,
1298
             'label':    device.label,
1299
             'label':    device.label,

+ 22
- 22
modules/RTC/ScreenObtainer.js Visa fil

1
 /* global chrome, $, alert */
1
 /* global chrome, $, alert */
2
 
2
 
3
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
-var logger = require('jitsi-meet-logger').getLogger(__filename);
5
-var RTCBrowserType = require('./RTCBrowserType');
3
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
+const logger = require('jitsi-meet-logger').getLogger(__filename);
5
+const RTCBrowserType = require('./RTCBrowserType');
6
 import JitsiTrackError from '../../JitsiTrackError';
6
 import JitsiTrackError from '../../JitsiTrackError';
7
 import * as JitsiTrackErrors from '../../JitsiTrackErrors';
7
 import * as JitsiTrackErrors from '../../JitsiTrackErrors';
8
 
8
 
10
  * Indicates whether the Chrome desktop sharing extension is installed.
10
  * Indicates whether the Chrome desktop sharing extension is installed.
11
  * @type {boolean}
11
  * @type {boolean}
12
  */
12
  */
13
-var chromeExtInstalled = false;
13
+let chromeExtInstalled = false;
14
 
14
 
15
 /**
15
 /**
16
  * Indicates whether an update of the Chrome desktop sharing extension is
16
  * Indicates whether an update of the Chrome desktop sharing extension is
17
  * required.
17
  * required.
18
  * @type {boolean}
18
  * @type {boolean}
19
  */
19
  */
20
-var chromeExtUpdateRequired = false;
20
+let chromeExtUpdateRequired = false;
21
 
21
 
22
 /**
22
 /**
23
  * Whether the jidesha extension for firefox is installed for the domain on
23
  * Whether the jidesha extension for firefox is installed for the domain on
24
  * which we are running. Null designates an unknown value.
24
  * which we are running. Null designates an unknown value.
25
  * @type {null}
25
  * @type {null}
26
  */
26
  */
27
-var firefoxExtInstalled = null;
27
+let firefoxExtInstalled = null;
28
 
28
 
29
 /**
29
 /**
30
  * If set to true, detection of an installed firefox extension will be started
30
  * If set to true, detection of an installed firefox extension will be started
31
  * again the next time obtainScreenOnFirefox is called (e.g. next time the
31
  * again the next time obtainScreenOnFirefox is called (e.g. next time the
32
  * user tries to enable screen sharing).
32
  * user tries to enable screen sharing).
33
  */
33
  */
34
-var reDetectFirefoxExtension = false;
34
+let reDetectFirefoxExtension = false;
35
 
35
 
36
-var gumFunction = null;
36
+let gumFunction = null;
37
 
37
 
38
 /**
38
 /**
39
  * The error returned by chrome when trying to start inline installation from
39
  * The error returned by chrome when trying to start inline installation from
58
 /**
58
 /**
59
  * Handles obtaining a stream from a screen capture on different browsers.
59
  * Handles obtaining a stream from a screen capture on different browsers.
60
  */
60
  */
61
-var ScreenObtainer = {
61
+const ScreenObtainer = {
62
     obtainStream: null,
62
     obtainStream: null,
63
 
63
 
64
     /**
64
     /**
69
      * @param gum {Function} GUM method
69
      * @param gum {Function} GUM method
70
      */
70
      */
71
     init(options, gum) {
71
     init(options, gum) {
72
-        var obtainDesktopStream = null;
72
+        let obtainDesktopStream = null;
73
         this.options = options = options || {};
73
         this.options = options = options || {};
74
         gumFunction = gum;
74
         gumFunction = gum;
75
 
75
 
82
                 window.JitsiMeetNW.obtainDesktopStream(
82
                 window.JitsiMeetNW.obtainDesktopStream(
83
                     onSuccess,
83
                     onSuccess,
84
                     (error, constraints) => {
84
                     (error, constraints) => {
85
-                        var jitsiError;
85
+                        let jitsiError;
86
                         // FIXME:
86
                         // FIXME:
87
                         // This is very very durty fix for recognising that the
87
                         // This is very very durty fix for recognising that the
88
                         // user have clicked the cancel button from the Desktop
88
                         // user have clicked the cancel button from the Desktop
182
      * @param errorCallback
182
      * @param errorCallback
183
      */
183
      */
184
     obtainScreenOnFirefox(options, callback, errorCallback) {
184
     obtainScreenOnFirefox(options, callback, errorCallback) {
185
-        var extensionRequired = false;
185
+        let extensionRequired = false;
186
         const { desktopSharingFirefoxMaxVersionExtRequired } = this.options;
186
         const { desktopSharingFirefoxMaxVersionExtRequired } = this.options;
187
         if (desktopSharingFirefoxMaxVersionExtRequired === -1
187
         if (desktopSharingFirefoxMaxVersionExtRequired === -1
188
             || (desktopSharingFirefoxMaxVersionExtRequired >= 0
188
             || (desktopSharingFirefoxMaxVersionExtRequired >= 0
349
  */
349
  */
350
 function isUpdateRequired(minVersion, extVersion) {
350
 function isUpdateRequired(minVersion, extVersion) {
351
     try {
351
     try {
352
-        var s1 = minVersion.split('.');
353
-        var s2 = extVersion.split('.');
352
+        const s1 = minVersion.split('.');
353
+        const s2 = extVersion.split('.');
354
 
354
 
355
-        var len = Math.max(s1.length, s2.length);
356
-        for (var i = 0; i < len; i++) {
357
-            var n1 = 0,
355
+        const len = Math.max(s1.length, s2.length);
356
+        for (let i = 0; i < len; i++) {
357
+            let n1 = 0,
358
                 n2 = 0;
358
                 n2 = 0;
359
 
359
 
360
             if (i < s1.length) {
360
             if (i < s1.length) {
399
                 return;
399
                 return;
400
             }
400
             }
401
             // Check installed extension version
401
             // Check installed extension version
402
-            var extVersion = response.version;
402
+            const extVersion = response.version;
403
             logger.log('Extension version is: ' + extVersion);
403
             logger.log('Extension version is: ' + extVersion);
404
-            var updateRequired
404
+            const updateRequired
405
                 = isUpdateRequired(
405
                 = isUpdateRequired(
406
                     options.desktopSharingChromeMinExtVersion,
406
                     options.desktopSharingChromeMinExtVersion,
407
                     extVersion);
407
                     extVersion);
422
         response => {
422
         response => {
423
             if (!response) {
423
             if (!response) {
424
                 // possibly re-wraping error message to make code consistent
424
                 // possibly re-wraping error message to make code consistent
425
-                var lastError = chrome.runtime.lastError;
425
+                const lastError = chrome.runtime.lastError;
426
                 failCallback(lastError instanceof Error
426
                 failCallback(lastError instanceof Error
427
                     ? lastError
427
                     ? lastError
428
                     : new JitsiTrackError(
428
                     : new JitsiTrackError(
544
         return;
544
         return;
545
     }
545
     }
546
 
546
 
547
-    var img = document.createElement('img');
547
+    const img = document.createElement('img');
548
     img.onload = () => {
548
     img.onload = () => {
549
         logger.log('Detected firefox screen sharing extension.');
549
         logger.log('Detected firefox screen sharing extension.');
550
         firefoxExtInstalled = true;
550
         firefoxExtInstalled = true;
558
     // "chrome://EXT_ID/content/DOMAIN.png"
558
     // "chrome://EXT_ID/content/DOMAIN.png"
559
     // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
559
     // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
560
     // DOMAIN is a domain whitelisted by the extension.
560
     // DOMAIN is a domain whitelisted by the extension.
561
-    var src = 'chrome://'
561
+    const src = 'chrome://'
562
         + options.desktopSharingFirefoxExtId.replace('@', '.')
562
         + options.desktopSharingFirefoxExtId.replace('@', '.')
563
         + '/content/' + document.location.hostname + '.png';
563
         + '/content/' + document.location.hostname + '.png';
564
     img.setAttribute('src', src);
564
     img.setAttribute('src', src);

+ 22
- 22
modules/RTC/TraceablePeerConnection.js Visa fil

40
  */
40
  */
41
 function TraceablePeerConnection(rtc, id, signalingLayer, ice_config,
41
 function TraceablePeerConnection(rtc, id, signalingLayer, ice_config,
42
                                  constraints, options) {
42
                                  constraints, options) {
43
-    var self = this;
43
+    const self = this;
44
     /**
44
     /**
45
      * The parent instance of RTC service which created this
45
      * The parent instance of RTC service which created this
46
      * <tt>TracablePeerConnection</tt>.
46
      * <tt>TracablePeerConnection</tt>.
58
      */
58
      */
59
     this.signalingLayer = signalingLayer;
59
     this.signalingLayer = signalingLayer;
60
     this.options = options;
60
     this.options = options;
61
-    var RTCPeerConnectionType = null;
61
+    let RTCPeerConnectionType = null;
62
     if (RTCBrowserType.isFirefox()) {
62
     if (RTCBrowserType.isFirefox()) {
63
         RTCPeerConnectionType = mozRTCPeerConnection;
63
         RTCPeerConnectionType = mozRTCPeerConnection;
64
     } else if (RTCBrowserType.isTemasysPluginUsed()) {
64
     } else if (RTCBrowserType.isTemasysPluginUsed()) {
74
      * @type {number}
74
      * @type {number}
75
      */
75
      */
76
     this.maxstats = 0;
76
     this.maxstats = 0;
77
-    var Interop = require('sdp-interop').Interop;
77
+    const Interop = require('sdp-interop').Interop;
78
     this.interop = new Interop();
78
     this.interop = new Interop();
79
-    var Simulcast = require('sdp-simulcast');
79
+    const Simulcast = require('sdp-simulcast');
80
     this.simulcast = new Simulcast({numOfLayers: SIMULCAST_LAYERS,
80
     this.simulcast = new Simulcast({numOfLayers: SIMULCAST_LAYERS,
81
         explodeRemoteSimulcast: false});
81
         explodeRemoteSimulcast: false});
82
     this.sdpConsistency = new SdpConsistency();
82
     this.sdpConsistency = new SdpConsistency();
169
     if (!RTCBrowserType.isFirefox() && this.maxstats) {
169
     if (!RTCBrowserType.isFirefox() && this.maxstats) {
170
         this.statsinterval = window.setInterval(function() {
170
         this.statsinterval = window.setInterval(function() {
171
             self.peerconnection.getStats(function(stats) {
171
             self.peerconnection.getStats(function(stats) {
172
-                var results = stats.result();
173
-                var now = new Date();
174
-                for (var i = 0; i < results.length; ++i) {
172
+                const results = stats.result();
173
+                const now = new Date();
174
+                for (let i = 0; i < results.length; ++i) {
175
                     results[i].names().forEach(function(name) {
175
                     results[i].names().forEach(function(name) {
176
-                        var id = results[i].id + '-' + name;
176
+                        const id = results[i].id + '-' + name;
177
                         if (!self.stats[id]) {
177
                         if (!self.stats[id]) {
178
                             self.stats[id] = {
178
                             self.stats[id] = {
179
                                 startTime: now,
179
                                 startTime: now,
200
 /**
200
 /**
201
  * Returns a string representation of a SessionDescription object.
201
  * Returns a string representation of a SessionDescription object.
202
  */
202
  */
203
-var dumpSDP = function(description) {
203
+const dumpSDP = function(description) {
204
     if (typeof description === 'undefined' || description == null) {
204
     if (typeof description === 'undefined' || description == null) {
205
         return '';
205
         return '';
206
     }
206
     }
497
  * Takes a SessionDescription object and returns a "normalized" version.
497
  * Takes a SessionDescription object and returns a "normalized" version.
498
  * Currently it only takes care of ordering the a=ssrc lines.
498
  * Currently it only takes care of ordering the a=ssrc lines.
499
  */
499
  */
500
-var normalizePlanB = function(desc) {
500
+const normalizePlanB = function(desc) {
501
     if (typeof desc !== 'object' || desc === null
501
     if (typeof desc !== 'object' || desc === null
502
         || typeof desc.sdp !== 'string') {
502
         || typeof desc.sdp !== 'string') {
503
         logger.warn('An empty description was passed as an argument.');
503
         logger.warn('An empty description was passed as an argument.');
504
         return desc;
504
         return desc;
505
     }
505
     }
506
 
506
 
507
-    var transform = require('sdp-transform');
508
-    var session = transform.parse(desc.sdp);
507
+    const transform = require('sdp-transform');
508
+    const session = transform.parse(desc.sdp);
509
 
509
 
510
     if (typeof session !== 'undefined'
510
     if (typeof session !== 'undefined'
511
         && typeof session.media !== 'undefined' && Array.isArray(session.media)) {
511
         && typeof session.media !== 'undefined' && Array.isArray(session.media)) {
518
             // the "a=ssrc:S1" lines, SRD fails.
518
             // the "a=ssrc:S1" lines, SRD fails.
519
             // So, put SSRC which appear as the first SSRC in an FID ssrc-group
519
             // So, put SSRC which appear as the first SSRC in an FID ssrc-group
520
             // first.
520
             // first.
521
-            var firstSsrcs = [];
522
-            var newSsrcLines = [];
521
+            const firstSsrcs = [];
522
+            const newSsrcLines = [];
523
 
523
 
524
             if (typeof mLine.ssrcGroups !== 'undefined'
524
             if (typeof mLine.ssrcGroups !== 'undefined'
525
                 && Array.isArray(mLine.ssrcGroups)) {
525
                 && Array.isArray(mLine.ssrcGroups)) {
534
             }
534
             }
535
 
535
 
536
             if (Array.isArray(mLine.ssrcs)) {
536
             if (Array.isArray(mLine.ssrcs)) {
537
-                var i;
537
+                let i;
538
                 for (i = 0; i < mLine.ssrcs.length; i++) {
538
                 for (i = 0; i < mLine.ssrcs.length; i++) {
539
                     if (typeof mLine.ssrcs[i] === 'object'
539
                     if (typeof mLine.ssrcs[i] === 'object'
540
                         && typeof mLine.ssrcs[i].id !== 'undefined'
540
                         && typeof mLine.ssrcs[i].id !== 'undefined'
555
         });
555
         });
556
     }
556
     }
557
 
557
 
558
-    var resStr = transform.write(session);
558
+    const resStr = transform.write(session);
559
     return new RTCSessionDescription({
559
     return new RTCSessionDescription({
560
         type: desc.type,
560
         type: desc.type,
561
         sdp: resStr
561
         sdp: resStr
562
     });
562
     });
563
 };
563
 };
564
 
564
 
565
-var getters = {
565
+const getters = {
566
     signalingState() {
566
     signalingState() {
567
         return this.peerconnection.signalingState;
567
         return this.peerconnection.signalingState;
568
     },
568
     },
570
         return this.peerconnection.iceConnectionState;
570
         return this.peerconnection.iceConnectionState;
571
     },
571
     },
572
     localDescription() {
572
     localDescription() {
573
-        var desc = this.peerconnection.localDescription;
573
+        let desc = this.peerconnection.localDescription;
574
 
574
 
575
         this.trace('getLocalDescription::preTransform', dumpSDP(desc));
575
         this.trace('getLocalDescription::preTransform', dumpSDP(desc));
576
 
576
 
583
         return desc;
583
         return desc;
584
     },
584
     },
585
     remoteDescription() {
585
     remoteDescription() {
586
-        var desc = this.peerconnection.remoteDescription;
586
+        let desc = this.peerconnection.remoteDescription;
587
         this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
587
         this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
588
 
588
 
589
         // if we're running on FF, transform to Plan B first.
589
         // if we're running on FF, transform to Plan B first.
654
             dumpSDP(description));
654
             dumpSDP(description));
655
             }
655
             }
656
 
656
 
657
-            var self = this;
657
+            const self = this;
658
             this.peerconnection.setLocalDescription(description,
658
             this.peerconnection.setLocalDescription(description,
659
         function() {
659
         function() {
660
             self.trace('setLocalDescriptionOnSuccess');
660
             self.trace('setLocalDescriptionOnSuccess');
700
                 description = normalizePlanB(description);
700
                 description = normalizePlanB(description);
701
             }
701
             }
702
 
702
 
703
-            var self = this;
703
+            const self = this;
704
             this.peerconnection.setRemoteDescription(description,
704
             this.peerconnection.setRemoteDescription(description,
705
         function() {
705
         function() {
706
             self.trace('setRemoteDescriptionOnSuccess');
706
             self.trace('setRemoteDescriptionOnSuccess');
765
  * @param {SDP} answer - the SDP to modify
765
  * @param {SDP} answer - the SDP to modify
766
  * @private
766
  * @private
767
  */
767
  */
768
-var _fixAnswerRFC4145Setup = function(offer, answer) {
768
+const _fixAnswerRFC4145Setup = function(offer, answer) {
769
     if (!RTCBrowserType.isChrome()) {
769
     if (!RTCBrowserType.isChrome()) {
770
         // It looks like Firefox doesn't agree with the fix (at least in its
770
         // It looks like Firefox doesn't agree with the fix (at least in its
771
         // current implementation) because it effectively remains active even
771
         // current implementation) because it effectively remains active even

+ 4
- 4
modules/connectivity/ConnectionQuality.js Visa fil

4
 import {getLogger} from 'jitsi-meet-logger';
4
 import {getLogger} from 'jitsi-meet-logger';
5
 import RTCBrowserType from '../RTC/RTCBrowserType';
5
 import RTCBrowserType from '../RTC/RTCBrowserType';
6
 
6
 
7
-var XMPPEvents = require('../../service/xmpp/XMPPEvents');
8
-var VideoType = require('../../service/RTC/VideoType');
9
-var Resolutions = require('../../service/RTC/Resolutions');
7
+const XMPPEvents = require('../../service/xmpp/XMPPEvents');
8
+const VideoType = require('../../service/RTC/VideoType');
9
+const Resolutions = require('../../service/RTC/Resolutions');
10
 
10
 
11
 const logger = getLogger(__filename);
11
 const logger = getLogger(__filename);
12
 
12
 
31
 /**
31
 /**
32
  * The initial bitrate for video in kbps.
32
  * The initial bitrate for video in kbps.
33
  */
33
  */
34
-var startBitrate = 800;
34
+let startBitrate = 800;
35
 
35
 
36
 /**
36
 /**
37
  * Gets the expected bitrate (in kbps) in perfect network conditions.
37
  * Gets the expected bitrate (in kbps) in perfect network conditions.

+ 2
- 2
modules/settings/Settings.js Visa fil

49
         this.userId;
49
         this.userId;
50
         this.callStatsUserName;
50
         this.callStatsUserName;
51
 
51
 
52
-        var localStorage = getLocalStorage();
52
+        const localStorage = getLocalStorage();
53
         if (localStorage) {
53
         if (localStorage) {
54
             this.userId
54
             this.userId
55
                 = localStorage.getItem('jitsiMeetId') || generateJitsiMeetId();
55
                 = localStorage.getItem('jitsiMeetId') || generateJitsiMeetId();
69
      * Save settings to localStorage if browser supports that.
69
      * Save settings to localStorage if browser supports that.
70
      */
70
      */
71
     save() {
71
     save() {
72
-        var localStorage = getLocalStorage();
72
+        const localStorage = getLocalStorage();
73
         if (localStorage) {
73
         if (localStorage) {
74
             localStorage.setItem('jitsiMeetId', this.userId);
74
             localStorage.setItem('jitsiMeetId', this.userId);
75
             localStorage.setItem('callStatsUserName', this.callStatsUserName);
75
             localStorage.setItem('callStatsUserName', this.callStatsUserName);

+ 14
- 14
modules/statistics/CallStats.js Visa fil

1
 /* global $, Strophe, callstats */
1
 /* global $, Strophe, callstats */
2
-var logger = require('jitsi-meet-logger').getLogger(__filename);
3
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
2
+const logger = require('jitsi-meet-logger').getLogger(__filename);
3
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
 import Settings from '../settings/Settings';
4
 import Settings from '../settings/Settings';
5
 
5
 
6
-var jsSHA = require('jssha');
7
-var io = require('socket.io-client');
6
+const jsSHA = require('jssha');
7
+const io = require('socket.io-client');
8
 
8
 
9
 /**
9
 /**
10
  * We define enumeration of wrtcFuncNames as we need them before
10
  * We define enumeration of wrtcFuncNames as we need them before
12
  * @const
12
  * @const
13
  * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
13
  * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
14
  */
14
  */
15
-var wrtcFuncNames = {
15
+const wrtcFuncNames = {
16
     createOffer:          'createOffer',
16
     createOffer:          'createOffer',
17
     createAnswer:         'createAnswer',
17
     createAnswer:         'createAnswer',
18
     setLocalDescription:  'setLocalDescription',
18
     setLocalDescription:  'setLocalDescription',
30
  * @const
30
  * @const
31
  * @see http://www.callstats.io/api/#enumeration-of-fabricevent
31
  * @see http://www.callstats.io/api/#enumeration-of-fabricevent
32
  */
32
  */
33
-var fabricEvent = {
33
+const fabricEvent = {
34
     fabricHold:'fabricHold',
34
     fabricHold:'fabricHold',
35
     fabricResume:'fabricResume',
35
     fabricResume:'fabricResume',
36
     audioMute:'audioMute',
36
     audioMute:'audioMute',
46
     activeDeviceList:'activeDeviceList'
46
     activeDeviceList:'activeDeviceList'
47
 };
47
 };
48
 
48
 
49
-var callStats = null;
49
+let callStats = null;
50
 
50
 
51
 /**
51
 /**
52
  * The user id to report to callstats as destination.
52
  * The user id to report to callstats as destination.
65
         return;
65
         return;
66
     }
66
     }
67
 
67
 
68
-    var ret = callStats.addNewFabric(this.peerconnection,
68
+    const ret = callStats.addNewFabric(this.peerconnection,
69
         DEFAULT_REMOTE_USER,
69
         DEFAULT_REMOTE_USER,
70
         callStats.fabricUsage.multiplex,
70
         callStats.fabricUsage.multiplex,
71
         this.confID,
71
         this.confID,
72
         this.pcCallback.bind(this));
72
         this.pcCallback.bind(this));
73
 
73
 
74
-    var fabricInitialized = ret.status === 'success';
74
+    const fabricInitialized = ret.status === 'success';
75
 
75
 
76
     if(!fabricInitialized) {
76
     if(!fabricInitialized) {
77
         CallStats.initializeFailed = true;
77
         CallStats.initializeFailed = true;
87
     if (CallStats.reportsQueue.length) {
87
     if (CallStats.reportsQueue.length) {
88
         CallStats.reportsQueue.forEach(function(report) {
88
         CallStats.reportsQueue.forEach(function(report) {
89
             if (report.type === reportType.ERROR) {
89
             if (report.type === reportType.ERROR) {
90
-                var error = report.data;
90
+                const error = report.data;
91
                 CallStats._reportError.call(this, error.type, error.error,
91
                 CallStats._reportError.call(this, error.type, error.error,
92
                     error.pc);
92
                     error.pc);
93
             } else if (report.type === reportType.EVENT
93
             } else if (report.type === reportType.EVENT
94
                 && fabricInitialized) {
94
                 && fabricInitialized) {
95
                 // if we have and event to report and we failed to add fabric
95
                 // if we have and event to report and we failed to add fabric
96
                 // this event will not be reported anyway, returning an error
96
                 // this event will not be reported anyway, returning an error
97
-                var eventData = report.data;
97
+                const eventData = report.data;
98
                 callStats.sendFabricEvent(
98
                 callStats.sendFabricEvent(
99
                     this.peerconnection,
99
                     this.peerconnection,
100
                     eventData.event,
100
                     eventData.event,
101
                     this.confID,
101
                     this.confID,
102
                     eventData.eventData);
102
                     eventData.eventData);
103
             } else if (report.type === reportType.MST_WITH_USERID) {
103
             } else if (report.type === reportType.MST_WITH_USERID) {
104
-                var data = report.data;
104
+                const data = report.data;
105
                 callStats.associateMstWithUserID(
105
                 callStats.associateMstWithUserID(
106
                     this.peerconnection,
106
                     this.peerconnection,
107
                     data.callStatsId,
107
                     data.callStatsId,
140
  * @param peerConnection {JingleSessionPC} the session object
140
  * @param peerConnection {JingleSessionPC} the session object
141
  * @param options {object} credentials for callstats.
141
  * @param options {object} credentials for callstats.
142
  */
142
  */
143
-var CallStats = _try_catch(function(jingleSession, options) {
143
+const CallStats = _try_catch(function(jingleSession, options) {
144
     try{
144
     try{
145
         CallStats.feedbackEnabled = false;
145
         CallStats.feedbackEnabled = false;
146
         callStats = new callstats($, io, jsSHA); // eslint-disable-line new-cap
146
         callStats = new callstats($, io, jsSHA); // eslint-disable-line new-cap
229
  * Type of pending reports, can be event or an error.
229
  * Type of pending reports, can be event or an error.
230
  * @type {{ERROR: string, EVENT: string}}
230
  * @type {{ERROR: string, EVENT: string}}
231
  */
231
  */
232
-var reportType = {
232
+const reportType = {
233
     ERROR: 'error',
233
     ERROR: 'error',
234
     EVENT: 'event',
234
     EVENT: 'event',
235
     MST_WITH_USERID: 'mstWithUserID'
235
     MST_WITH_USERID: 'mstWithUserID'

+ 14
- 14
modules/statistics/LocalStatsCollector.js Visa fil

2
  * Provides statistics for the local stream.
2
  * Provides statistics for the local stream.
3
  */
3
  */
4
 
4
 
5
-var RTCBrowserType = require('../RTC/RTCBrowserType');
5
+const RTCBrowserType = require('../RTC/RTCBrowserType');
6
 
6
 
7
 /**
7
 /**
8
  * Size of the webaudio analyzer buffer.
8
  * Size of the webaudio analyzer buffer.
9
  * @type {number}
9
  * @type {number}
10
  */
10
  */
11
-var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
11
+const WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
12
 
12
 
13
 /**
13
 /**
14
  * Value of the webaudio analyzer smoothing time parameter.
14
  * Value of the webaudio analyzer smoothing time parameter.
15
  * @type {number}
15
  * @type {number}
16
  */
16
  */
17
-var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
17
+const WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
18
 
18
 
19
 window.AudioContext = window.AudioContext || window.webkitAudioContext;
19
 window.AudioContext = window.AudioContext || window.webkitAudioContext;
20
 
20
 
21
-var context = null;
21
+let context = null;
22
 
22
 
23
 if(window.AudioContext) {
23
 if(window.AudioContext) {
24
     context = new AudioContext();
24
     context = new AudioContext();
41
  */
41
  */
42
 function timeDomainDataToAudioLevel(samples) {
42
 function timeDomainDataToAudioLevel(samples) {
43
 
43
 
44
-    var maxVolume = 0;
44
+    let maxVolume = 0;
45
 
45
 
46
-    var length = samples.length;
46
+    const length = samples.length;
47
 
47
 
48
-    for (var i = 0; i < length; i++) {
48
+    for (let i = 0; i < length; i++) {
49
         if (maxVolume < samples[i]) {
49
         if (maxVolume < samples[i]) {
50
             maxVolume = samples[i];
50
             maxVolume = samples[i];
51
         }
51
         }
61
  * @returns {Number} the audio level to be set
61
  * @returns {Number} the audio level to be set
62
  */
62
  */
63
 function animateLevel(newLevel, lastLevel) {
63
 function animateLevel(newLevel, lastLevel) {
64
-    var value = 0;
65
-    var diff = lastLevel - newLevel;
64
+    let value = 0;
65
+    const diff = lastLevel - newLevel;
66
     if(diff > 0.2) {
66
     if(diff > 0.2) {
67
         value = lastLevel - 0.2;
67
         value = lastLevel - 0.2;
68
     } else if(diff < -0.4) {
68
     } else if(diff < -0.4) {
100
         return;
100
         return;
101
     }
101
     }
102
     context.resume();
102
     context.resume();
103
-    var analyser = context.createAnalyser();
103
+    const analyser = context.createAnalyser();
104
     analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
104
     analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
105
     analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
105
     analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
106
 
106
 
107
-    var source = context.createMediaStreamSource(this.stream);
107
+    const source = context.createMediaStreamSource(this.stream);
108
     source.connect(analyser);
108
     source.connect(analyser);
109
 
109
 
110
 
110
 
111
-    var self = this;
111
+    const self = this;
112
 
112
 
113
     this.intervalId = setInterval(
113
     this.intervalId = setInterval(
114
         function() {
114
         function() {
115
-            var array = new Uint8Array(analyser.frequencyBinCount);
115
+            const array = new Uint8Array(analyser.frequencyBinCount);
116
             analyser.getByteTimeDomainData(array);
116
             analyser.getByteTimeDomainData(array);
117
-            var audioLevel = timeDomainDataToAudioLevel(array);
117
+            const audioLevel = timeDomainDataToAudioLevel(array);
118
             if (audioLevel != self.audioLevel) {
118
             if (audioLevel != self.audioLevel) {
119
                 self.audioLevel = animateLevel(audioLevel, self.audioLevel);
119
                 self.audioLevel = animateLevel(audioLevel, self.audioLevel);
120
                 self.callback(self.audioLevel);
120
                 self.callback(self.audioLevel);

+ 60
- 58
modules/statistics/RTPStatsCollector.js Visa fil

1
 /* global require */
1
 /* global require */
2
 
2
 
3
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
-var logger = require('jitsi-meet-logger').getLogger(__filename);
5
-var RTCBrowserType = require('../RTC/RTCBrowserType');
3
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
4
+const logger = require('jitsi-meet-logger').getLogger(__filename);
5
+const RTCBrowserType = require('../RTC/RTCBrowserType');
6
 import * as StatisticsEvents from '../../service/statistics/Events';
6
 import * as StatisticsEvents from '../../service/statistics/Events';
7
 
7
 
8
 /* Whether we support the browser we are running into for logging statistics */
8
 /* Whether we support the browser we are running into for logging statistics */
9
-var browserSupported = RTCBrowserType.isChrome()
9
+const browserSupported = RTCBrowserType.isChrome()
10
         || RTCBrowserType.isOpera() || RTCBrowserType.isFirefox()
10
         || RTCBrowserType.isOpera() || RTCBrowserType.isFirefox()
11
         || RTCBrowserType.isNWJS() || RTCBrowserType.isElectron();
11
         || RTCBrowserType.isNWJS() || RTCBrowserType.isElectron();
12
 
12
 
14
  * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
14
  * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
15
  * by RTCPeerConnection#getStats mapped by RTCBrowserType.
15
  * by RTCPeerConnection#getStats mapped by RTCBrowserType.
16
  */
16
  */
17
-var KEYS_BY_BROWSER_TYPE = {};
17
+const KEYS_BY_BROWSER_TYPE = {};
18
 KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
18
 KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
19
     'ssrc': 'ssrc',
19
     'ssrc': 'ssrc',
20
     'packetsReceived': 'packetsReceived',
20
     'packetsReceived': 'packetsReceived',
179
      * @private
179
      * @private
180
      */
180
      */
181
     this._browserType = RTCBrowserType.getBrowserType();
181
     this._browserType = RTCBrowserType.getBrowserType();
182
-    var keys = KEYS_BY_BROWSER_TYPE[this._browserType];
182
+    const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
183
     if (!keys) {
183
     if (!keys) {
184
         throw 'The browser type \'' + this._browserType + '\' isn\'t supported!';
184
         throw 'The browser type \'' + this._browserType + '\' isn\'t supported!';
185
     }
185
     }
241
  * Starts stats updates.
241
  * Starts stats updates.
242
  */
242
  */
243
 StatsCollector.prototype.start = function(startAudioLevelStats) {
243
 StatsCollector.prototype.start = function(startAudioLevelStats) {
244
-    var self = this;
244
+    const self = this;
245
     if(startAudioLevelStats) {
245
     if(startAudioLevelStats) {
246
         this.audioLevelsIntervalId = setInterval(
246
         this.audioLevelsIntervalId = setInterval(
247
             function() {
247
             function() {
248
                 // Interval updates
248
                 // Interval updates
249
                 self.peerconnection.getStats(
249
                 self.peerconnection.getStats(
250
                     function(report) {
250
                     function(report) {
251
-                        var results = null;
251
+                        let results = null;
252
                         if (!report || !report.result
252
                         if (!report || !report.result
253
                             || typeof report.result != 'function') {
253
                             || typeof report.result != 'function') {
254
                             results = report;
254
                             results = report;
273
                 // Interval updates
273
                 // Interval updates
274
                 self.peerconnection.getStats(
274
                 self.peerconnection.getStats(
275
                     function(report) {
275
                     function(report) {
276
-                        var results = null;
276
+                        let results = null;
277
                         if (!report || !report.result
277
                         if (!report || !report.result
278
                             || typeof report.result != 'function') {
278
                             || typeof report.result != 'function') {
279
                             // firefox
279
                             // firefox
312
     // Define the function which converts a LibJitsiMeet browser-asnostic name
312
     // Define the function which converts a LibJitsiMeet browser-asnostic name
313
     // to a browser-specific key of a report returned by
313
     // to a browser-specific key of a report returned by
314
     // RTCPeerConnection#getStats.
314
     // RTCPeerConnection#getStats.
315
-    var keyFromName = function(name) {
316
-        var key = keys[name];
315
+    const keyFromName = function(name) {
316
+        const key = keys[name];
317
         if (key) {
317
         if (key) {
318
             return key;
318
             return key;
319
         }
319
         }
324
     // Define the function which retrieves the value from a specific report
324
     // Define the function which retrieves the value from a specific report
325
     // returned by RTCPeerConnection#getStats associated with a given
325
     // returned by RTCPeerConnection#getStats associated with a given
326
     // browser-specific key.
326
     // browser-specific key.
327
-    var itemStatByKey;
327
+    let itemStatByKey;
328
     switch (this._browserType) {
328
     switch (this._browserType) {
329
     case RTCBrowserType.RTC_BROWSER_CHROME:
329
     case RTCBrowserType.RTC_BROWSER_CHROME:
330
     case RTCBrowserType.RTC_BROWSER_OPERA:
330
     case RTCBrowserType.RTC_BROWSER_OPERA:
344
         // Objective-C WebRTC API: RTCStatsReport has a values property of type
344
         // Objective-C WebRTC API: RTCStatsReport has a values property of type
345
         // Array in which each element is a key-value pair.
345
         // Array in which each element is a key-value pair.
346
         itemStatByKey = function(item, key) {
346
         itemStatByKey = function(item, key) {
347
-            var value;
347
+            let value;
348
             item.values.some(function(pair) {
348
             item.values.some(function(pair) {
349
                 if (pair.hasOwnProperty(key)) {
349
                 if (pair.hasOwnProperty(key)) {
350
                     value = pair[key];
350
                     value = pair[key];
376
         return;
376
         return;
377
     }
377
     }
378
 
378
 
379
-    var getStatValue = this._getStatValue;
379
+    const getStatValue = this._getStatValue;
380
     function getNonNegativeStat(report, name) {
380
     function getNonNegativeStat(report, name) {
381
-        var value = getStatValue(report, name);
381
+        let value = getStatValue(report, name);
382
         if (typeof value !== 'number') {
382
         if (typeof value !== 'number') {
383
             value = Number(value);
383
             value = Number(value);
384
         }
384
         }
389
 
389
 
390
         return Math.max(0, value);
390
         return Math.max(0, value);
391
     }
391
     }
392
-    var byteSentStats = {};
392
+    const byteSentStats = {};
393
 
393
 
394
-    for (var idx in this.currentStatsReport) {
394
+    for (const idx in this.currentStatsReport) {
395
         if(!this.currentStatsReport.hasOwnProperty(idx)) {
395
         if(!this.currentStatsReport.hasOwnProperty(idx)) {
396
             continue;
396
             continue;
397
         }
397
         }
398
-        var now = this.currentStatsReport[idx];
398
+        const now = this.currentStatsReport[idx];
399
         try {
399
         try {
400
-            var receiveBandwidth = getStatValue(now, 'receiveBandwidth');
401
-            var sendBandwidth = getStatValue(now, 'sendBandwidth');
400
+            const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
401
+            const sendBandwidth = getStatValue(now, 'sendBandwidth');
402
             if (receiveBandwidth || sendBandwidth) {
402
             if (receiveBandwidth || sendBandwidth) {
403
                 this.conferenceStats.bandwidth = {
403
                 this.conferenceStats.bandwidth = {
404
                     'download': Math.round(receiveBandwidth / 1000),
404
                     'download': Math.round(receiveBandwidth / 1000),
408
         } catch(e) {/* not supported*/}
408
         } catch(e) {/* not supported*/}
409
 
409
 
410
         if(now.type == 'googCandidatePair') {
410
         if(now.type == 'googCandidatePair') {
411
-            var active, ip, localip, type;
411
+            let active, ip, localip, type;
412
             try {
412
             try {
413
                 ip = getStatValue(now, 'remoteAddress');
413
                 ip = getStatValue(now, 'remoteAddress');
414
                 type = getStatValue(now, 'transportType');
414
                 type = getStatValue(now, 'transportType');
419
                 continue;
419
                 continue;
420
             }
420
             }
421
             // Save the address unless it has been saved already.
421
             // Save the address unless it has been saved already.
422
-            var conferenceStatsTransport = this.conferenceStats.transport;
422
+            const conferenceStatsTransport = this.conferenceStats.transport;
423
             if(!conferenceStatsTransport.some(
423
             if(!conferenceStatsTransport.some(
424
                     t =>
424
                     t =>
425
                         t.ip == ip && t.type == type && t.localip == localip)) {
425
                         t.ip == ip && t.type == type && t.localip == localip)) {
433
                 continue;
433
                 continue;
434
             }
434
             }
435
 
435
 
436
-            var local = this.currentStatsReport[now.localCandidateId];
437
-            var remote = this.currentStatsReport[now.remoteCandidateId];
436
+            const local = this.currentStatsReport[now.localCandidateId];
437
+            const remote = this.currentStatsReport[now.remoteCandidateId];
438
             this.conferenceStats.transport.push({
438
             this.conferenceStats.transport.push({
439
                 ip: remote.ipAddress + ':' + remote.portNumber,
439
                 ip: remote.ipAddress + ':' + remote.portNumber,
440
                 type: local.transport,
440
                 type: local.transport,
447
             continue;
447
             continue;
448
         }
448
         }
449
 
449
 
450
-        var before = this.previousStatsReport[idx];
451
-        var ssrc = getStatValue(now, 'ssrc');
450
+        const before = this.previousStatsReport[idx];
451
+        const ssrc = getStatValue(now, 'ssrc');
452
         if (!before || !ssrc) {
452
         if (!before || !ssrc) {
453
             continue;
453
             continue;
454
         }
454
         }
455
 
455
 
456
-        var ssrcStats
456
+        const ssrcStats
457
           = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
457
           = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
458
 
458
 
459
-        var isDownloadStream = true;
460
-        var key = 'packetsReceived';
461
-        var packetsNow = getStatValue(now, key);
459
+        let isDownloadStream = true;
460
+        let key = 'packetsReceived';
461
+        let packetsNow = getStatValue(now, key);
462
         if (typeof packetsNow === 'undefined'
462
         if (typeof packetsNow === 'undefined'
463
             || packetsNow === null || packetsNow === '') {
463
             || packetsNow === null || packetsNow === '') {
464
             isDownloadStream = false;
464
             isDownloadStream = false;
473
             packetsNow = 0;
473
             packetsNow = 0;
474
         }
474
         }
475
 
475
 
476
-        var packetsBefore = getNonNegativeStat(before, key);
477
-        var packetsDiff = Math.max(0, packetsNow - packetsBefore);
476
+        const packetsBefore = getNonNegativeStat(before, key);
477
+        const packetsDiff = Math.max(0, packetsNow - packetsBefore);
478
 
478
 
479
-        var packetsLostNow = getNonNegativeStat(now, 'packetsLost');
480
-        var packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
481
-        var packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
479
+        const packetsLostNow = getNonNegativeStat(now, 'packetsLost');
480
+        const packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
481
+        const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
482
 
482
 
483
         ssrcStats.setLoss({
483
         ssrcStats.setLoss({
484
             packetsTotal: packetsDiff + packetsLostDiff,
484
             packetsTotal: packetsDiff + packetsLostDiff,
486
             isDownloadStream
486
             isDownloadStream
487
         });
487
         });
488
 
488
 
489
-        var bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
490
-        var bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
491
-        var bytesReceived = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
489
+        const bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
490
+        const bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
491
+        const bytesReceived = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
492
 
492
 
493
-        var bytesSent = 0;
493
+        let bytesSent = 0;
494
 
494
 
495
         // TODO: clean this mess up!
495
         // TODO: clean this mess up!
496
-        var nowBytesTransmitted = getStatValue(now, 'bytesSent');
496
+        let nowBytesTransmitted = getStatValue(now, 'bytesSent');
497
         if(typeof nowBytesTransmitted === 'number'
497
         if(typeof nowBytesTransmitted === 'number'
498
             || typeof nowBytesTransmitted === 'string') {
498
             || typeof nowBytesTransmitted === 'string') {
499
             nowBytesTransmitted = Number(nowBytesTransmitted);
499
             nowBytesTransmitted = Number(nowBytesTransmitted);
507
         }
507
         }
508
         bytesSent = Math.max(0, bytesSent);
508
         bytesSent = Math.max(0, bytesSent);
509
 
509
 
510
-        var timeMs = now.timestamp - before.timestamp;
511
-        var bitrateReceivedKbps = 0, bitrateSentKbps = 0;
510
+        const timeMs = now.timestamp - before.timestamp;
511
+        let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
512
         if (timeMs > 0) {
512
         if (timeMs > 0) {
513
             // TODO is there any reason to round here?
513
             // TODO is there any reason to round here?
514
             bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
514
             bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
520
             'upload': bitrateSentKbps
520
             'upload': bitrateSentKbps
521
         });
521
         });
522
 
522
 
523
-        var resolution = {height: null, width: null};
523
+        const resolution = {height: null, width: null};
524
         try {
524
         try {
525
-            var height, width;
525
+            let height, width;
526
             if ((height = getStatValue(now, 'googFrameHeightReceived'))
526
             if ((height = getStatValue(now, 'googFrameHeightReceived'))
527
                 && (width = getStatValue(now, 'googFrameWidthReceived'))) {
527
                 && (width = getStatValue(now, 'googFrameWidthReceived'))) {
528
                 resolution.height = height;
528
                 resolution.height = height;
542
     }
542
     }
543
 
543
 
544
     // process stats
544
     // process stats
545
-    var totalPackets = {
545
+    const totalPackets = {
546
         download: 0,
546
         download: 0,
547
         upload: 0
547
         upload: 0
548
     };
548
     };
549
-    var lostPackets = {
549
+    const lostPackets = {
550
         download: 0,
550
         download: 0,
551
         upload: 0
551
         upload: 0
552
     };
552
     };
553
-    var bitrateDownload = 0;
554
-    var bitrateUpload = 0;
555
-    var resolutions = {};
553
+    let bitrateDownload = 0;
554
+    let bitrateUpload = 0;
555
+    const resolutions = {};
556
     Object.keys(this.ssrc2stats).forEach(
556
     Object.keys(this.ssrc2stats).forEach(
557
         function(ssrc) {
557
         function(ssrc) {
558
-            var ssrcStats = this.ssrc2stats[ssrc];
558
+            const ssrcStats = this.ssrc2stats[ssrc];
559
             // process packet loss stats
559
             // process packet loss stats
560
-            var loss = ssrcStats.loss;
561
-            var type = loss.isDownloadStream ? 'download' : 'upload';
560
+            const loss = ssrcStats.loss;
561
+            const type = loss.isDownloadStream ? 'download' : 'upload';
562
             totalPackets[type] += loss.packetsTotal;
562
             totalPackets[type] += loss.packetsTotal;
563
             lostPackets[type] += loss.packetsLost;
563
             lostPackets[type] += loss.packetsLost;
564
 
564
 
606
         return;
606
         return;
607
     }
607
     }
608
 
608
 
609
-    var getStatValue = this._getStatValue;
609
+    const getStatValue = this._getStatValue;
610
 
610
 
611
-    for(var idx in this.currentAudioLevelsReport) {
611
+    for(const idx in this.currentAudioLevelsReport) {
612
         if(!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
612
         if(!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
613
             continue;
613
             continue;
614
         }
614
         }
615
-        var now = this.currentAudioLevelsReport[idx];
615
+        const now = this.currentAudioLevelsReport[idx];
616
 
616
 
617
         if (now.type != 'ssrc') {
617
         if (now.type != 'ssrc') {
618
             continue;
618
             continue;
619
         }
619
         }
620
 
620
 
621
-        var before = this.baselineAudioLevelsReport[idx];
622
-        var ssrc = getStatValue(now, 'ssrc');
621
+        const before = this.baselineAudioLevelsReport[idx];
622
+        const ssrc = getStatValue(now, 'ssrc');
623
         if (!before) {
623
         if (!before) {
624
             logger.warn(ssrc + ' not enough data');
624
             logger.warn(ssrc + ' not enough data');
625
             continue;
625
             continue;
633
         }
633
         }
634
 
634
 
635
         // Audio level
635
         // Audio level
636
+        let audioLevel;
637
+
636
         try {
638
         try {
637
-            var audioLevel
639
+            audioLevel
638
                 = getStatValue(now, 'audioInputLevel')
640
                 = getStatValue(now, 'audioInputLevel')
639
                     || getStatValue(now, 'audioOutputLevel');
641
                     || getStatValue(now, 'audioOutputLevel');
640
         } catch(e) {/* not supported*/
642
         } catch(e) {/* not supported*/

+ 12
- 12
modules/statistics/statistics.js Visa fil

1
 /* global require */
1
 /* global require */
2
 import analytics from './AnalyticsAdapter';
2
 import analytics from './AnalyticsAdapter';
3
-var CallStats = require('./CallStats');
4
-var EventEmitter = require('events');
3
+const CallStats = require('./CallStats');
4
+const EventEmitter = require('events');
5
 import JitsiTrackError from '../../JitsiTrackError';
5
 import JitsiTrackError from '../../JitsiTrackError';
6
-var logger = require('jitsi-meet-logger').getLogger(__filename);
7
-var LocalStats = require('./LocalStatsCollector.js');
8
-var RTPStats = require('./RTPStatsCollector.js');
9
-var ScriptUtil = require('../util/ScriptUtil');
6
+const logger = require('jitsi-meet-logger').getLogger(__filename);
7
+const LocalStats = require('./LocalStatsCollector.js');
8
+const RTPStats = require('./RTPStatsCollector.js');
9
+const ScriptUtil = require('../util/ScriptUtil');
10
 import * as StatisticsEvents from '../../service/statistics/Events';
10
 import * as StatisticsEvents from '../../service/statistics/Events';
11
 
11
 
12
 /**
12
 /**
13
  * True if callstats API is loaded
13
  * True if callstats API is loaded
14
  */
14
  */
15
-var isCallstatsLoaded = false;
15
+let isCallstatsLoaded = false;
16
 
16
 
17
 // Since callstats.io is a third party, we cannot guarantee the quality of their
17
 // Since callstats.io is a third party, we cannot guarantee the quality of their
18
 // service. More specifically, their server may take noticeably long time to
18
 // service. More specifically, their server may take noticeably long time to
42
  * @param {JitsiTrackError} error
42
  * @param {JitsiTrackError} error
43
  */
43
  */
44
 function formatJitsiTrackErrorForCallStats(error) {
44
 function formatJitsiTrackErrorForCallStats(error) {
45
-    var err = new Error();
45
+    const err = new Error();
46
 
46
 
47
     // Just copy original stack from error
47
     // Just copy original stack from error
48
     err.stack = error.stack;
48
     err.stack = error.stack;
128
     if(!Statistics.audioLevelsEnabled) {
128
     if(!Statistics.audioLevelsEnabled) {
129
         return;
129
         return;
130
     }
130
     }
131
-    var localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
131
+    const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
132
         callback);
132
         callback);
133
     this.localStats.push(localStats);
133
     this.localStats.push(localStats);
134
     localStats.start();
134
     localStats.start();
190
         return;
190
         return;
191
     }
191
     }
192
 
192
 
193
-    for(var i = 0; i < Statistics.localStats.length; i++) {
193
+    for(let i = 0; i < Statistics.localStats.length; i++) {
194
         if(Statistics.localStats[i].stream === stream) {
194
         if(Statistics.localStats[i].stream === stream) {
195
-            var localStats = Statistics.localStats.splice(i, 1);
195
+            const localStats = Statistics.localStats.splice(i, 1);
196
             localStats[0].stop();
196
             localStats[0].stop();
197
             break;
197
             break;
198
         }
198
         }
229
  */
229
  */
230
 Statistics.prototype.stopCallStats = function() {
230
 Statistics.prototype.stopCallStats = function() {
231
     if(this.callStatsStarted) {
231
     if(this.callStatsStarted) {
232
-        var index = Statistics.callsStatsInstances.indexOf(this.callstats);
232
+        const index = Statistics.callsStatsInstances.indexOf(this.callstats);
233
         if(index > -1) {
233
         if(index > -1) {
234
             Statistics.callsStatsInstances.splice(index, 1);
234
             Statistics.callsStatsInstances.splice(index, 1);
235
         }
235
         }

+ 22
- 22
modules/transcription/audioRecorder.js Visa fil

1
 /* global MediaRecorder, MediaStream, webkitMediaStream */
1
 /* global MediaRecorder, MediaStream, webkitMediaStream */
2
 
2
 
3
-var RecordingResult = require('./recordingResult');
3
+const RecordingResult = require('./recordingResult');
4
 
4
 
5
 /**
5
 /**
6
  * Possible audio formats MIME types
6
  * Possible audio formats MIME types
7
  */
7
  */
8
-var AUDIO_WEBM = 'audio/webm';    // Supported in chrome
9
-var AUDIO_OGG = 'audio/ogg';     // Supported in firefox
8
+const AUDIO_WEBM = 'audio/webm';    // Supported in chrome
9
+const AUDIO_OGG = 'audio/ogg';     // Supported in firefox
10
 
10
 
11
 /**
11
 /**
12
  * A TrackRecorder object holds all the information needed for recording a
12
  * A TrackRecorder object holds all the information needed for recording a
13
  * single JitsiTrack (either remote or local)
13
  * single JitsiTrack (either remote or local)
14
  * @param track The JitsiTrack the object is going to hold
14
  * @param track The JitsiTrack the object is going to hold
15
  */
15
  */
16
-var TrackRecorder = function(track) {
16
+const TrackRecorder = function(track) {
17
     // The JitsiTrack holding the stream
17
     // The JitsiTrack holding the stream
18
     this.track = track;
18
     this.track = track;
19
     // The MediaRecorder recording the stream
19
     // The MediaRecorder recording the stream
61
  * @param track the JitsiTrack holding the audio MediaStream(s)
61
  * @param track the JitsiTrack holding the audio MediaStream(s)
62
  */
62
  */
63
 function instantiateTrackRecorder(track) {
63
 function instantiateTrackRecorder(track) {
64
-    var trackRecorder = new TrackRecorder(track);
64
+    const trackRecorder = new TrackRecorder(track);
65
     // Create a new stream which only holds the audio track
65
     // Create a new stream which only holds the audio track
66
-    var originalStream = trackRecorder.track.getOriginalStream();
67
-    var stream = createEmptyStream();
66
+    const originalStream = trackRecorder.track.getOriginalStream();
67
+    const stream = createEmptyStream();
68
     originalStream.getAudioTracks().forEach(function(track) {
68
     originalStream.getAudioTracks().forEach(function(track) {
69
         stream.addTrack(track);
69
         stream.addTrack(track);
70
     });
70
     });
105
  * @param jitsiConference the jitsiConference which this object
105
  * @param jitsiConference the jitsiConference which this object
106
  * is going to record
106
  * is going to record
107
  */
107
  */
108
-var audioRecorder = function(jitsiConference) {
108
+const audioRecorder = function(jitsiConference) {
109
     // array of TrackRecorders, where each trackRecorder
109
     // array of TrackRecorders, where each trackRecorder
110
     // holds the JitsiTrack, MediaRecorder and recorder data
110
     // holds the JitsiTrack, MediaRecorder and recorder data
111
     this.recorders = [];
111
     this.recorders = [];
133
 audioRecorder.prototype.addTrack = function(track) {
133
 audioRecorder.prototype.addTrack = function(track) {
134
     if(track.isAudioTrack()) {
134
     if(track.isAudioTrack()) {
135
         // create the track recorder
135
         // create the track recorder
136
-        var trackRecorder = instantiateTrackRecorder(track);
136
+        const trackRecorder = instantiateTrackRecorder(track);
137
         // push it to the local array of all recorders
137
         // push it to the local array of all recorders
138
         this.recorders.push(trackRecorder);
138
         this.recorders.push(trackRecorder);
139
         // update the name of the trackRecorders
139
         // update the name of the trackRecorders
161
         return;
161
         return;
162
     }
162
     }
163
 
163
 
164
-    var array = this.recorders;
165
-    var i;
164
+    const array = this.recorders;
165
+    let i;
166
     for(i = 0; i < array.length; i++) {
166
     for(i = 0; i < array.length; i++) {
167
         if(array[i].track.getParticipantId() === track.getParticipantId()) {
167
         if(array[i].track.getParticipantId() === track.getParticipantId()) {
168
-            var recorderToRemove = array[i];
168
+            const recorderToRemove = array[i];
169
             if(this.isRecording) {
169
             if(this.isRecording) {
170
                 stopRecorder(recorderToRemove);
170
                 stopRecorder(recorderToRemove);
171
             } else {
171
             } else {
185
  * undefined value, the old value will also be kept.
185
  * undefined value, the old value will also be kept.
186
  */
186
  */
187
 audioRecorder.prototype.updateNames = function() {
187
 audioRecorder.prototype.updateNames = function() {
188
-    var conference = this.jitsiConference;
188
+    const conference = this.jitsiConference;
189
     this.recorders.forEach(function(trackRecorder) {
189
     this.recorders.forEach(function(trackRecorder) {
190
         if(trackRecorder.track.isLocal()) {
190
         if(trackRecorder.track.isLocal()) {
191
             trackRecorder.name = 'the transcriber';
191
             trackRecorder.name = 'the transcriber';
192
         } else {
192
         } else {
193
-            var id = trackRecorder.track.getParticipantId();
194
-            var participant = conference.getParticipantById(id);
195
-            var newName = participant.getDisplayName();
193
+            const id = trackRecorder.track.getParticipantId();
194
+            const participant = conference.getParticipantById(id);
195
+            const newName = participant.getDisplayName();
196
             if(newName !== 'undefined') {
196
             if(newName !== 'undefined') {
197
                 trackRecorder.name = newName;
197
                 trackRecorder.name = newName;
198
             }
198
             }
236
  * link hacking to download all recorded audio streams
236
  * link hacking to download all recorded audio streams
237
  */
237
  */
238
 audioRecorder.prototype.download = function() {
238
 audioRecorder.prototype.download = function() {
239
-    var t = this;
239
+    const t = this;
240
     this.recorders.forEach(function(trackRecorder) {
240
     this.recorders.forEach(function(trackRecorder) {
241
-        var blob = new Blob(trackRecorder.data, {type: t.fileType});
242
-        var url = URL.createObjectURL(blob);
243
-        var a = document.createElement('a');
241
+        const blob = new Blob(trackRecorder.data, {type: t.fileType});
242
+        const url = URL.createObjectURL(blob);
243
+        const a = document.createElement('a');
244
         document.body.appendChild(a);
244
         document.body.appendChild(a);
245
         a.style = 'display: none';
245
         a.style = 'display: none';
246
         a.href = url;
246
         a.href = url;
263
     // make sure the names are up to date before sending them off
263
     // make sure the names are up to date before sending them off
264
     this.updateNames();
264
     this.updateNames();
265
 
265
 
266
-    var array = [];
267
-    var t = this;
266
+    const array = [];
267
+    const t = this;
268
     this.recorders.forEach(function(recorder) {
268
     this.recorders.forEach(function(recorder) {
269
         array.push(
269
         array.push(
270
             new RecordingResult(
270
             new RecordingResult(

+ 1
- 1
modules/transcription/recordingResult.js Visa fil

8
  * @param wordArray the recorder audio stream transcribed as an array of Word
8
  * @param wordArray the recorder audio stream transcribed as an array of Word
9
  *                  objects
9
  *                  objects
10
  */
10
  */
11
-var RecordingResult = function(blob, name, startTime, wordArray) {
11
+const RecordingResult = function(blob, name, startTime, wordArray) {
12
     this.blob = blob;
12
     this.blob = blob;
13
     this.name = name;
13
     this.name = name;
14
     this.startTime = startTime;
14
     this.startTime = startTime;

+ 22
- 22
modules/transcription/transcriber.js Visa fil

1
-var AudioRecorder = require('./audioRecorder');
2
-var SphinxService = require(
1
+const AudioRecorder = require('./audioRecorder');
2
+const SphinxService = require(
3
     './transcriptionServices/SphinxTranscriptionService');
3
     './transcriptionServices/SphinxTranscriptionService');
4
 
4
 
5
-var BEFORE_STATE = 'before';
6
-var RECORDING_STATE = 'recording';
7
-var TRANSCRIBING_STATE = 'transcribing';
8
-var FINISHED_STATE = 'finished';
5
+const BEFORE_STATE = 'before';
6
+const RECORDING_STATE = 'recording';
7
+const TRANSCRIBING_STATE = 'transcribing';
8
+const FINISHED_STATE = 'finished';
9
 
9
 
10
 // the amount of characters each line in the transcription will have
10
 // the amount of characters each line in the transcription will have
11
-var MAXIMUM_SENTENCE_LENGTH = 80;
11
+const MAXIMUM_SENTENCE_LENGTH = 80;
12
 
12
 
13
 /**
13
 /**
14
  * This is the main object for handing the Transcription. It interacts with
14
  * This is the main object for handing the Transcription. It interacts with
17
  * will be merged to create a transcript
17
  * will be merged to create a transcript
18
  * @param {AudioRecorder} audioRecorder An audioRecorder recording a conference
18
  * @param {AudioRecorder} audioRecorder An audioRecorder recording a conference
19
  */
19
  */
20
-var transcriber = function() {
20
+const transcriber = function() {
21
     // the object which can record all audio in the conference
21
     // the object which can record all audio in the conference
22
     this.audioRecorder = new AudioRecorder();
22
     this.audioRecorder = new AudioRecorder();
23
     // this object can send the recorder audio to a speech-to-text service
23
     // this object can send the recorder audio to a speech-to-text service
76
     console.log('stopping recording and sending audio files');
76
     console.log('stopping recording and sending audio files');
77
     this.audioRecorder.stop();
77
     this.audioRecorder.stop();
78
     // and send all recorded audio the the transcription service
78
     // and send all recorded audio the the transcription service
79
-    var t = this;
79
+    const t = this;
80
 
80
 
81
-    var callBack = blobCallBack.bind(this);
81
+    const callBack = blobCallBack.bind(this);
82
     this.audioRecorder.getRecordingResults().forEach(function(recordingResult) {
82
     this.audioRecorder.getRecordingResults().forEach(function(recordingResult) {
83
         t.transcriptionService.send(recordingResult, callBack);
83
         t.transcriptionService.send(recordingResult, callBack);
84
         t.counter++;
84
         t.counter++;
99
  * @param {RecordingResult} answer a RecordingResult object with a defined
99
  * @param {RecordingResult} answer a RecordingResult object with a defined
100
  * WordArray
100
  * WordArray
101
  */
101
  */
102
-var blobCallBack = function(answer) {
102
+const blobCallBack = function(answer) {
103
     console.log(
103
     console.log(
104
         'retrieved an answer from the transcription service. The answer has an'
104
         'retrieved an answer from the transcription service. The answer has an'
105
             + ' array of length: ' + answer.wordArray.length);
105
             + ' array of length: ' + answer.wordArray.length);
106
     // first add the offset between the start of the transcription and
106
     // first add the offset between the start of the transcription and
107
     // the start of the recording to all start and end times
107
     // the start of the recording to all start and end times
108
     if(answer.wordArray.length > 0) {
108
     if(answer.wordArray.length > 0) {
109
-        var offset = answer.startTime.getUTCMilliseconds()
109
+        let offset = answer.startTime.getUTCMilliseconds()
110
             - this.startTime.getUTCMilliseconds();
110
             - this.startTime.getUTCMilliseconds();
111
         // transcriber time will always be earlier
111
         // transcriber time will always be earlier
112
         if (offset < 0) {
112
         if (offset < 0) {
113
             offset = 0; // presume 0 if it somehow not earlier
113
             offset = 0; // presume 0 if it somehow not earlier
114
         }
114
         }
115
 
115
 
116
-        var array = '[';
116
+        let array = '[';
117
         answer.wordArray.forEach(function(wordObject) {
117
         answer.wordArray.forEach(function(wordObject) {
118
             wordObject.begin += offset;
118
             wordObject.begin += offset;
119
             wordObject.end += offset;
119
             wordObject.end += offset;
160
     // previously placed word, while removing the selected word from its array
160
     // previously placed word, while removing the selected word from its array
161
     // note: words can be skipped the skipped word's begin and end time somehow
161
     // note: words can be skipped the skipped word's begin and end time somehow
162
     // end up between the closest word start and end time
162
     // end up between the closest word start and end time
163
-    var arrays = this.results;
163
+    const arrays = this.results;
164
     // arrays of Word objects
164
     // arrays of Word objects
165
-    var potentialWords = []; // array of the first Word objects
165
+    const potentialWords = []; // array of the first Word objects
166
     // check if any arrays are already empty and remove them
166
     // check if any arrays are already empty and remove them
167
     hasPopulatedArrays(arrays);
167
     hasPopulatedArrays(arrays);
168
 
168
 
172
     });
172
     });
173
 
173
 
174
     // keep adding words to transcription until all arrays are exhausted
174
     // keep adding words to transcription until all arrays are exhausted
175
-    var lowestWordArray;
176
-    var wordToAdd;
177
-    var foundSmaller;
175
+    let lowestWordArray;
176
+    let wordToAdd;
177
+    let foundSmaller;
178
     while(hasPopulatedArrays(arrays)) {
178
     while(hasPopulatedArrays(arrays)) {
179
         // first select the lowest array;
179
         // first select the lowest array;
180
         lowestWordArray = arrays[0];
180
         lowestWordArray = arrays[0];
238
  * @param {Array<Array>} twoDimensionalArray the array to check
238
  * @param {Array<Array>} twoDimensionalArray the array to check
239
  * @returns {boolean} true if any non-zero arrays inside, otherwise false
239
  * @returns {boolean} true if any non-zero arrays inside, otherwise false
240
  */
240
  */
241
-var hasPopulatedArrays = function(twoDimensionalArray) {
242
-    var i;
241
+const hasPopulatedArrays = function(twoDimensionalArray) {
242
+    let i;
243
     for(i = 0; i < twoDimensionalArray.length; i++) {
243
     for(i = 0; i < twoDimensionalArray.length; i++) {
244
         if(twoDimensionalArray[i].length === 0) {
244
         if(twoDimensionalArray[i].length === 0) {
245
             twoDimensionalArray.splice(i, 1);
245
             twoDimensionalArray.splice(i, 1);
256
  * @param {Array<Word>} array the sorted array to push to
256
  * @param {Array<Word>} array the sorted array to push to
257
  * @param {Word} word the word to push into the array
257
  * @param {Word} word the word to push into the array
258
  */
258
  */
259
-var pushWordToSortedArray = function(array, word) {
259
+const pushWordToSortedArray = function(array, word) {
260
     if(array.length === 0) {
260
     if(array.length === 0) {
261
         array.push(word);
261
         array.push(word);
262
     } else{
262
     } else{
264
             array.push(word);
264
             array.push(word);
265
             return;
265
             return;
266
         }
266
         }
267
-        var i;
267
+        let i;
268
         for(i = 0; i < array.length; i++) {
268
         for(i = 0; i < array.length; i++) {
269
             if(word.begin < array[i].begin) {
269
             if(word.begin < array[i].begin) {
270
                 array.splice(i, 0, word);
270
                 array.splice(i, 0, word);

+ 1
- 1
modules/transcription/transcriberHolder.js Visa fil

5
  * This is probably temporary until there is a better way to expose the
5
  * This is probably temporary until there is a better way to expose the
6
  * Transcriber in a conference
6
  * Transcriber in a conference
7
  */
7
  */
8
-var transcriberHolder = {
8
+const transcriberHolder = {
9
     transcribers : [],
9
     transcribers : [],
10
 
10
 
11
     add(transcriber) {
11
     add(transcriber) {

+ 2
- 2
modules/transcription/transcriptionServices/AbstractTranscriptionService.js Visa fil

2
  * Abstract class representing an interface to implement a speech-to-text
2
  * Abstract class representing an interface to implement a speech-to-text
3
  * service on.
3
  * service on.
4
  */
4
  */
5
-var TranscriptionService = function() {
5
+const TranscriptionService = function() {
6
     throw new Error('TranscriptionService is abstract and cannot be'
6
     throw new Error('TranscriptionService is abstract and cannot be'
7
         + 'created');
7
         + 'created');
8
 };
8
 };
17
  *        the answer as a WordArray
17
  *        the answer as a WordArray
18
  */
18
  */
19
 TranscriptionService.prototype.send = function send(recordingResult, callback) {
19
 TranscriptionService.prototype.send = function send(recordingResult, callback) {
20
-    var t = this;
20
+    const t = this;
21
     this.sendRequest(recordingResult.blob, function(response) {
21
     this.sendRequest(recordingResult.blob, function(response) {
22
         if(!t.verify(response)) {
22
         if(!t.verify(response)) {
23
             console.log('the retrieved response from the server'
23
             console.log('the retrieved response from the server'

+ 11
- 11
modules/transcription/transcriptionServices/SphinxTranscriptionService.js Visa fil

1
 /* global config */
1
 /* global config */
2
 
2
 
3
-var TranscriptionService = require('./AbstractTranscriptionService');
4
-var Word = require('../word');
5
-var audioRecorder = require('./../audioRecorder');
3
+const TranscriptionService = require('./AbstractTranscriptionService');
4
+const Word = require('../word');
5
+const audioRecorder = require('./../audioRecorder');
6
 
6
 
7
 /**
7
 /**
8
  * Implements a TranscriptionService for a Sphinx4 http server
8
  * Implements a TranscriptionService for a Sphinx4 http server
9
  */
9
  */
10
-var SphinxService = function() {
10
+const SphinxService = function() {
11
     // set the correct url
11
     // set the correct url
12
     this.url = getURL();
12
     this.url = getURL();
13
 };
13
 };
32
 SphinxService.prototype.sendRequest = function(audioFileBlob, callback) {
32
 SphinxService.prototype.sendRequest = function(audioFileBlob, callback) {
33
     console.log('sending an audio file  to ' + this.url);
33
     console.log('sending an audio file  to ' + this.url);
34
     console.log('the audio file being sent: ' + audioFileBlob);
34
     console.log('the audio file being sent: ' + audioFileBlob);
35
-    var request = new XMLHttpRequest();
35
+    const request = new XMLHttpRequest();
36
     request.onreadystatechange = function() {
36
     request.onreadystatechange = function() {
37
         if(request.readyState === XMLHttpRequest.DONE
37
         if(request.readyState === XMLHttpRequest.DONE
38
             && request.status === 200) {
38
             && request.status === 200) {
57
  * @param response the JSON body retrieved from the Sphinx4 server
57
  * @param response the JSON body retrieved from the Sphinx4 server
58
  */
58
  */
59
 SphinxService.prototype.formatResponse = function(response) {
59
 SphinxService.prototype.formatResponse = function(response) {
60
-    var result = JSON.parse(response).objects;
60
+    const result = JSON.parse(response).objects;
61
     // make sure to delete the session id object, which is always
61
     // make sure to delete the session id object, which is always
62
     // the first value in the JSON array
62
     // the first value in the JSON array
63
     result.shift();
63
     result.shift();
64
-    var array = [];
64
+    const array = [];
65
     result.forEach(function(word) {
65
     result.forEach(function(word) {
66
         if(!word.filler) {
66
         if(!word.filler) {
67
             array.push(new Word(word.word, word.start, word.end));
67
             array.push(new Word(word.word, word.start, word.end));
82
         return false;
82
         return false;
83
     }
83
     }
84
     // test if the string can be parsed into valid JSON
84
     // test if the string can be parsed into valid JSON
85
-    var json;
85
+    let json;
86
     try{
86
     try{
87
         json = JSON.parse(response);
87
         json = JSON.parse(response);
88
     } catch (error) {
88
     } catch (error) {
94
         return false;
94
         return false;
95
     }
95
     }
96
     // get the "objects" value and check for a session ID
96
     // get the "objects" value and check for a session ID
97
-    var array = json.objects;
97
+    const array = json.objects;
98
     if(!(array[0] && array[0]['session-id'])) {
98
     if(!(array[0] && array[0]['session-id'])) {
99
         return false;
99
         return false;
100
     }
100
     }
109
  * @returns {string} the URL to the sphinx4 server
109
  * @returns {string} the URL to the sphinx4 server
110
  */
110
  */
111
 function getURL() {
111
 function getURL() {
112
-    var message = 'config does not contain an url to a '
112
+    const message = 'config does not contain an url to a '
113
     + 'Sphinx4 https server';
113
     + 'Sphinx4 https server';
114
     if(config.sphinxURL === undefined) {
114
     if(config.sphinxURL === undefined) {
115
         console.log(message);
115
         console.log(message);
116
     } else {
116
     } else {
117
-        var toReturn = config.sphinxURL;
117
+        const toReturn = config.sphinxURL;
118
         if(toReturn.includes !== undefined && toReturn.includes('https://')) {
118
         if(toReturn.includes !== undefined && toReturn.includes('https://')) {
119
             return toReturn;
119
             return toReturn;
120
         }
120
         }

+ 1
- 1
modules/transcription/word.js Visa fil

4
  * @param begin the time the word was started being uttered
4
  * @param begin the time the word was started being uttered
5
  * @param end the time the word stopped being uttered
5
  * @param end the time the word stopped being uttered
6
  */
6
  */
7
-var Word = function(word, begin, end) {
7
+const Word = function(word, begin, end) {
8
     this.word = word;
8
     this.word = word;
9
     this.begin = begin;
9
     this.begin = begin;
10
     this.end = end;
10
     this.end = end;

+ 2
- 2
modules/util/AuthUtil.js Visa fil

1
-var AuthUtil = {
1
+const AuthUtil = {
2
     /**
2
     /**
3
      * Creates the URL pointing to JWT token authentication service. It is
3
      * Creates the URL pointing to JWT token authentication service. It is
4
      * formatted from the 'urlPattern' argument which can contain the following
4
      * formatted from the 'urlPattern' argument which can contain the following
21
      * constructed.
21
      * constructed.
22
      */
22
      */
23
     getTokenAuthUrl(urlPattern, roomName, roleUpgrade) {
23
     getTokenAuthUrl(urlPattern, roomName, roleUpgrade) {
24
-        var url = urlPattern;
24
+        const url = urlPattern;
25
         if (typeof url !== 'string') {
25
         if (typeof url !== 'string') {
26
             return null;
26
             return null;
27
         }
27
         }

+ 2
- 2
modules/util/EventEmitterForwarder.js Visa fil

24
  */
24
  */
25
 EventEmitterForwarder.prototype.forward = function() {
25
 EventEmitterForwarder.prototype.forward = function() {
26
     // This line is only for fixing jshint errors.
26
     // This line is only for fixing jshint errors.
27
-    var args = arguments;
28
-    var srcEvent = args[0];
27
+    const args = arguments;
28
+    const srcEvent = args[0];
29
     // This will be the "this" value for emit function.
29
     // This will be the "this" value for emit function.
30
     args[0] = this.dest;
30
     args[0] = this.dest;
31
     // Using bind.apply to pass the arguments as Array-like object ("arguments")
31
     // Using bind.apply to pass the arguments as Array-like object ("arguments")

+ 6
- 6
modules/util/GlobalOnErrorHandler.js Visa fil

9
 /**
9
 /**
10
  * List with global error handlers that will be executed.
10
  * List with global error handlers that will be executed.
11
  */
11
  */
12
-var handlers = [];
12
+const handlers = [];
13
 
13
 
14
 // If an old handler exists, also fire its events.
14
 // If an old handler exists, also fire its events.
15
-var oldOnErrorHandler = window.onerror;
15
+const oldOnErrorHandler = window.onerror;
16
 
16
 
17
 /**
17
 /**
18
  * Custom error handler that calls the old global error handler and executes
18
  * Custom error handler that calls the old global error handler and executes
28
 }
28
 }
29
 
29
 
30
 // If an old handler exists, also fire its events.
30
 // If an old handler exists, also fire its events.
31
-var oldOnUnhandledRejection = window.onunhandledrejection;
31
+const oldOnUnhandledRejection = window.onunhandledrejection;
32
 
32
 
33
 /**
33
 /**
34
  * Custom handler that calls the old global handler and executes all handlers
34
  * Custom handler that calls the old global handler and executes all handlers
48
 window.onunhandledrejection = JitsiGlobalUnhandledRejection;
48
 window.onunhandledrejection = JitsiGlobalUnhandledRejection;
49
 
49
 
50
 
50
 
51
-var GlobalOnErrorHandler = {
51
+const GlobalOnErrorHandler = {
52
     /**
52
     /**
53
      * Adds new error handlers.
53
      * Adds new error handlers.
54
      * @param handler the new handler.
54
      * @param handler the new handler.
61
      * @param error the error to pass to the error handler
61
      * @param error the error to pass to the error handler
62
      */
62
      */
63
     callErrorHandler(error) {
63
     callErrorHandler(error) {
64
-        var errHandler = window.onerror;
64
+        const errHandler = window.onerror;
65
         if(!errHandler) {
65
         if(!errHandler) {
66
             return;
66
             return;
67
         }
67
         }
72
      * @param error the error to pass to the rejection handler.
72
      * @param error the error to pass to the rejection handler.
73
      */
73
      */
74
     callUnhandledRejectionHandler(error) {
74
     callUnhandledRejectionHandler(error) {
75
-        var errHandler = window.onunhandledrejection;
75
+        const errHandler = window.onunhandledrejection;
76
         if(!errHandler) {
76
         if(!errHandler) {
77
             return;
77
             return;
78
         }
78
         }

+ 7
- 7
modules/util/RandomUtil.js Visa fil

1
-/**
2
 /**
1
 /**
3
  * @const
2
  * @const
4
  */
3
  */
5
-var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
4
+const ALPHANUM
5
+    = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
6
 
6
 
7
 /**
7
 /**
8
  * Hexadecimal digits.
8
  * Hexadecimal digits.
9
  * @const
9
  * @const
10
  */
10
  */
11
-var HEX_DIGITS = '0123456789abcdef';
11
+const HEX_DIGITS = '0123456789abcdef';
12
 
12
 
13
 /**
13
 /**
14
  * Generates random int within the range [min, max]
14
  * Generates random int within the range [min, max]
35
  * @returns {string} random string of specified length
35
  * @returns {string} random string of specified length
36
  */
36
  */
37
 function randomAlphanumStr(length) {
37
 function randomAlphanumStr(length) {
38
-    var result = '';
38
+    let result = '';
39
 
39
 
40
-    for (var i = 0; i < length; i += 1) {
40
+    for (let i = 0; i < length; i += 1) {
41
         result += randomElement(ALPHANUM);
41
         result += randomElement(ALPHANUM);
42
     }
42
     }
43
 
43
 
47
 /**
47
 /**
48
  * Exported interface.
48
  * Exported interface.
49
  */
49
  */
50
-var RandomUtil = {
50
+const RandomUtil = {
51
     /**
51
     /**
52
      * Returns a random hex digit.
52
      * Returns a random hex digit.
53
      * @returns {*}
53
      * @returns {*}
60
      * @param len the length.
60
      * @param len the length.
61
      */
61
      */
62
     randomHexString(len) {
62
     randomHexString(len) {
63
-        var ret = '';
63
+        let ret = '';
64
         while (len--) {
64
         while (len--) {
65
             ret += this.randomHexDigit();
65
             ret += this.randomHexDigit();
66
         }
66
         }

+ 9
- 9
modules/util/ScriptUtil.js Visa fil

1
-var currentExecutingScript = require('current-executing-script');
1
+const currentExecutingScript = require('current-executing-script');
2
 
2
 
3
 
3
 
4
 /**
4
 /**
5
  * Implements utility functions which facilitate the dealing with scripts such
5
  * Implements utility functions which facilitate the dealing with scripts such
6
  * as the download and execution of a JavaScript file.
6
  * as the download and execution of a JavaScript file.
7
  */
7
  */
8
-var ScriptUtil = {
8
+const ScriptUtil = {
9
     /**
9
     /**
10
      * Loads a script from a specific source.
10
      * Loads a script from a specific source.
11
      *
11
      *
23
      */
23
      */
24
     loadScript(src, async, prepend, relativeURL,
24
     loadScript(src, async, prepend, relativeURL,
25
                           loadCallback, errorCallback) {
25
                           loadCallback, errorCallback) {
26
-        var d = document;
27
-        var tagName = 'script';
28
-        var script = d.createElement(tagName);
29
-        var referenceNode = d.getElementsByTagName(tagName)[0];
26
+        const d = document;
27
+        const tagName = 'script';
28
+        const script = d.createElement(tagName);
29
+        const referenceNode = d.getElementsByTagName(tagName)[0];
30
 
30
 
31
         script.async = async;
31
         script.async = async;
32
 
32
 
33
         if (relativeURL) {
33
         if (relativeURL) {
34
             // finds the src url of the current loaded script
34
             // finds the src url of the current loaded script
35
             // and use it as base of the src supplied argument
35
             // and use it as base of the src supplied argument
36
-            var scriptEl = currentExecutingScript();
36
+            const scriptEl = currentExecutingScript();
37
             if(scriptEl) {
37
             if(scriptEl) {
38
-                var scriptSrc = scriptEl.src;
39
-                var baseScriptSrc
38
+                const scriptSrc = scriptEl.src;
39
+                const baseScriptSrc
40
                     = scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);
40
                     = scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);
41
                 if (scriptSrc && baseScriptSrc) {
41
                 if (scriptSrc && baseScriptSrc) {
42
                     src = baseScriptSrc + src;
42
                     src = baseScriptSrc + src;

+ 4
- 4
modules/util/UsernameGenerator.js Visa fil

1
-var RandomUtil = require('./RandomUtil');
1
+const RandomUtil = require('./RandomUtil');
2
 
2
 
3
 /**
3
 /**
4
  * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
4
  * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
7
  *
7
  *
8
  * @const
8
  * @const
9
  */
9
  */
10
-var names = [
10
+const names = [
11
     'Aaliyah', 'Aaron', 'Abagail', 'Abbey', 'Abbie', 'Abbigail', 'Abby',
11
     'Aaliyah', 'Aaron', 'Abagail', 'Abbey', 'Abbie', 'Abbigail', 'Abby',
12
     'Abdiel', 'Abdul', 'Abdullah', 'Abe', 'Abel', 'Abelardo', 'Abigail',
12
     'Abdiel', 'Abdul', 'Abdullah', 'Abe', 'Abel', 'Abelardo', 'Abigail',
13
     'Abigale', 'Abigayle', 'Abner', 'Abraham', 'Ada', 'Adah', 'Adalberto',
13
     'Abigale', 'Abigayle', 'Abner', 'Abraham', 'Ada', 'Adah', 'Adalberto',
430
  * @returns {string} random username
430
  * @returns {string} random username
431
  */
431
  */
432
 function generateUsername() {
432
 function generateUsername() {
433
-    var name = RandomUtil.randomElement(names);
434
-    var suffix = RandomUtil.randomAlphanumStr(3);
433
+    const name = RandomUtil.randomElement(names);
434
+    const suffix = RandomUtil.randomAlphanumStr(3);
435
 
435
 
436
     return name + '-' + suffix;
436
     return name + '-' + suffix;
437
 }
437
 }

+ 5
- 5
modules/version/ComponentsVersions.js Visa fil

1
-var logger = require('jitsi-meet-logger').getLogger(__filename);
2
-var Statistics = require('../statistics/statistics');
1
+const logger = require('jitsi-meet-logger').getLogger(__filename);
2
+const Statistics = require('../statistics/statistics');
3
 
3
 
4
 /**
4
 /**
5
  * The constant for the name of the focus component.
5
  * The constant for the name of the focus component.
48
             return;
48
             return;
49
         }
49
         }
50
 
50
 
51
-        var log = [];
51
+        const log = [];
52
         node.children.forEach(function(item) {
52
         node.children.forEach(function(item) {
53
 
53
 
54
-            var componentName = item.attributes.name;
54
+            const componentName = item.attributes.name;
55
             if (componentName !== ComponentsVersions.FOCUS_COMPONENT
55
             if (componentName !== ComponentsVersions.FOCUS_COMPONENT
56
             && componentName !== ComponentsVersions.XMPP_SERVER_COMPONENT
56
             && componentName !== ComponentsVersions.XMPP_SERVER_COMPONENT
57
             && componentName !== ComponentsVersions.VIDEOBRIDGE_COMPONENT) {
57
             && componentName !== ComponentsVersions.VIDEOBRIDGE_COMPONENT) {
61
                 return;
61
                 return;
62
             }
62
             }
63
 
63
 
64
-            var version = item.value;
64
+            const version = item.value;
65
             if (this.versions[componentName] !== version) {
65
             if (this.versions[componentName] !== version) {
66
                 this.versions[componentName] = version;
66
                 this.versions[componentName] = version;
67
                 logger.info('Got ' + componentName + ' version: ' + version);
67
                 logger.info('Got ' + componentName + ' version: ' + version);

+ 55
- 51
modules/xmpp/ChatRoom.js Visa fil

9
 
9
 
10
 const logger = getLogger(__filename);
10
 const logger = getLogger(__filename);
11
 
11
 
12
-var parser = {
12
+const parser = {
13
     packet2JSON(packet, nodes) {
13
     packet2JSON(packet, nodes) {
14
-        var self = this;
14
+        const self = this;
15
         $(packet).children().each(function() {
15
         $(packet).children().each(function() {
16
-            var tagName = $(this).prop('tagName');
16
+            const tagName = $(this).prop('tagName');
17
             const node = {
17
             const node = {
18
                 tagName
18
                 tagName
19
             };
19
             };
21
             $($(this)[0].attributes).each(function(index, attr) {
21
             $($(this)[0].attributes).each(function(index, attr) {
22
                 node.attributes[ attr.name ] = attr.value;
22
                 node.attributes[ attr.name ] = attr.value;
23
             });
23
             });
24
-            var text = Strophe.getText($(this)[0]);
24
+            const text = Strophe.getText($(this)[0]);
25
             if (text) {
25
             if (text) {
26
                 node.value = text;
26
                 node.value = text;
27
             }
27
             }
55
  * @param nodeName the name of the node (videomuted, audiomuted, etc)
55
  * @param nodeName the name of the node (videomuted, audiomuted, etc)
56
  */
56
  */
57
 function filterNodeFromPresenceJSON(pres, nodeName) {
57
 function filterNodeFromPresenceJSON(pres, nodeName) {
58
-    var res = [];
58
+    const res = [];
59
     for(let i = 0; i < pres.length; i++) {
59
     for(let i = 0; i < pres.length; i++) {
60
         if(pres[i].tagName === nodeName) {
60
         if(pres[i].tagName === nodeName) {
61
             res.push(pres[i]);
61
             res.push(pres[i]);
126
 
126
 
127
     join(password) {
127
     join(password) {
128
         this.password = password;
128
         this.password = password;
129
-        var self = this;
129
+        const self = this;
130
         this.moderator.allocateConferenceFocus(function() {
130
         this.moderator.allocateConferenceFocus(function() {
131
             self.sendPresence(true);
131
             self.sendPresence(true);
132
         });
132
         });
133
     }
133
     }
134
 
134
 
135
     sendPresence(fromJoin) {
135
     sendPresence(fromJoin) {
136
-        var to = this.presMap.to;
136
+        const to = this.presMap.to;
137
         if (!to || (!this.joined && !fromJoin)) {
137
         if (!to || (!this.joined && !fromJoin)) {
138
             // Too early to send presence - not initialized
138
             // Too early to send presence - not initialized
139
             return;
139
             return;
140
         }
140
         }
141
 
141
 
142
-        var pres = $pres({to });
142
+        const pres = $pres({to });
143
 
143
 
144
         // xep-0045 defines: "including in the initial presence stanza an empty
144
         // xep-0045 defines: "including in the initial presence stanza an empty
145
         // <x/> element qualified by the 'http://jabber.org/protocol/muc' namespace"
145
         // <x/> element qualified by the 'http://jabber.org/protocol/muc' namespace"
172
      */
172
      */
173
     doLeave() {
173
     doLeave() {
174
         logger.log('do leave', this.myroomjid);
174
         logger.log('do leave', this.myroomjid);
175
-        var pres = $pres({to: this.myroomjid, type: 'unavailable' });
175
+        const pres = $pres({to: this.myroomjid, type: 'unavailable' });
176
         this.presMap.length = 0;
176
         this.presMap.length = 0;
177
 
177
 
178
         // XXX Strophe is asynchronously sending by default. Unfortunately, that
178
         // XXX Strophe is asynchronously sending by default. Unfortunately, that
194
     discoRoomInfo() {
194
     discoRoomInfo() {
195
       // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
195
       // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
196
 
196
 
197
-        var getInfo = $iq({type: 'get', to: this.roomjid})
197
+        const getInfo = $iq({type: 'get', to: this.roomjid})
198
         .c('query', {xmlns: Strophe.NS.DISCO_INFO});
198
         .c('query', {xmlns: Strophe.NS.DISCO_INFO});
199
 
199
 
200
         this.connection.sendIQ(getInfo, function(result) {
200
         this.connection.sendIQ(getInfo, function(result) {
201
-            var locked = $(result).find('>query>feature[var="muc_passwordprotected"]')
201
+            const locked = $(result).find('>query>feature[var="muc_passwordprotected"]')
202
             .length === 1;
202
             .length === 1;
203
             if (locked != this.locked) {
203
             if (locked != this.locked) {
204
                 this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
204
                 this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
214
     createNonAnonymousRoom() {
214
     createNonAnonymousRoom() {
215
         // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
215
         // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
216
 
216
 
217
-        var getForm = $iq({type: 'get', to: this.roomjid})
217
+        const getForm = $iq({type: 'get', to: this.roomjid})
218
             .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
218
             .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
219
             .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
219
             .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
220
 
220
 
221
-        var self = this;
221
+        const self = this;
222
 
222
 
223
         this.connection.sendIQ(getForm, function(form) {
223
         this.connection.sendIQ(getForm, function(form) {
224
 
224
 
225
             if (!$(form).find(
225
             if (!$(form).find(
226
                     '>query>x[xmlns="jabber:x:data"]'
226
                     '>query>x[xmlns="jabber:x:data"]'
227
                     + '>field[var="muc#roomconfig_whois"]').length) {
227
                     + '>field[var="muc#roomconfig_whois"]').length) {
228
-                var errmsg = 'non-anonymous rooms not supported';
228
+                const errmsg = 'non-anonymous rooms not supported';
229
                 GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
229
                 GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
230
                 logger.error(errmsg);
230
                 logger.error(errmsg);
231
                 return;
231
                 return;
232
             }
232
             }
233
 
233
 
234
-            var formSubmit = $iq({to: self.roomjid, type: 'set'})
234
+            const formSubmit = $iq({to: self.roomjid, type: 'set'})
235
                 .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
235
                 .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
236
 
236
 
237
             formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
237
             formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
252
     }
252
     }
253
 
253
 
254
     onPresence(pres) {
254
     onPresence(pres) {
255
-        var from = pres.getAttribute('from');
255
+        const from = pres.getAttribute('from');
256
         // Parse roles.
256
         // Parse roles.
257
-        var member = {};
257
+        const member = {};
258
         member.show = $(pres).find('>show').text();
258
         member.show = $(pres).find('>show').text();
259
         member.status = $(pres).find('>status').text();
259
         member.status = $(pres).find('>status').text();
260
-        var mucUserItem
260
+        const mucUserItem
261
             = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
261
             = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
262
         member.affiliation = mucUserItem.attr('affiliation');
262
         member.affiliation = mucUserItem.attr('affiliation');
263
         member.role = mucUserItem.attr('role');
263
         member.role = mucUserItem.attr('role');
264
 
264
 
265
         // Focus recognition
265
         // Focus recognition
266
-        var jid = mucUserItem.attr('jid');
266
+        const jid = mucUserItem.attr('jid');
267
         member.jid = jid;
267
         member.jid = jid;
268
         member.isFocus
268
         member.isFocus
269
             = jid && jid.indexOf(this.moderator.getFocusUserJid() + '/') === 0;
269
             = jid && jid.indexOf(this.moderator.getFocusUserJid() + '/') === 0;
273
                     === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
273
                     === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
274
 
274
 
275
         $(pres).find('>x').remove();
275
         $(pres).find('>x').remove();
276
-        var nodes = [];
276
+        const nodes = [];
277
         parser.packet2JSON(pres, nodes);
277
         parser.packet2JSON(pres, nodes);
278
         this.lastPresences[from] = nodes;
278
         this.lastPresences[from] = nodes;
279
         let jibri = null;
279
         let jibri = null;
292
         }
292
         }
293
 
293
 
294
         if (from == this.myroomjid) {
294
         if (from == this.myroomjid) {
295
-            var newRole = member.affiliation == 'owner' ? member.role : 'none';
295
+            const newRole = member.affiliation == 'owner' ? member.role : 'none';
296
             if (this.role !== newRole) {
296
             if (this.role !== newRole) {
297
                 this.role = newRole;
297
                 this.role = newRole;
298
                 this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
298
                 this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
299
             }
299
             }
300
             if (!this.joined) {
300
             if (!this.joined) {
301
                 this.joined = true;
301
                 this.joined = true;
302
-                var now = this.connectionTimes['muc.joined']
302
+                const now = this.connectionTimes['muc.joined']
303
                     = window.performance.now();
303
                     = window.performance.now();
304
                 logger.log('(TIME) MUC joined:\t', now);
304
                 logger.log('(TIME) MUC joined:\t', now);
305
 
305
 
324
         } else {
324
         } else {
325
             // Presence update for existing participant
325
             // Presence update for existing participant
326
             // Watch role change:
326
             // Watch role change:
327
-            var memberOfThis = this.members[from];
327
+            const memberOfThis = this.members[from];
328
             if (memberOfThis.role != member.role) {
328
             if (memberOfThis.role != member.role) {
329
                 memberOfThis.role = member.role;
329
                 memberOfThis.role = member.role;
330
                 this.eventEmitter.emit(
330
                 this.eventEmitter.emit(
357
             switch(node.tagName) {
357
             switch(node.tagName) {
358
             case 'nick':
358
             case 'nick':
359
                 if(!member.isFocus) {
359
                 if(!member.isFocus) {
360
-                    var displayName = this.xmpp.options.displayJids
360
+                    const displayName = this.xmpp.options.displayJids
361
                             ? Strophe.getResourceFromJid(from) : member.nick;
361
                             ? Strophe.getResourceFromJid(from) : member.nick;
362
 
362
 
363
                     if (displayName && displayName.length > 0) {
363
                     if (displayName && displayName.length > 0) {
375
             case 'jibri-recording-status':
375
             case 'jibri-recording-status':
376
                 jibri = node;
376
                 jibri = node;
377
                 break;
377
                 break;
378
-            case 'call-control':
379
-                var att = node.attributes;
378
+            case 'call-control': {
379
+                const att = node.attributes;
380
                 if(!att) {
380
                 if(!att) {
381
                     break;
381
                     break;
382
                 }
382
                 }
384
                 this.phonePin = att.pin || null;
384
                 this.phonePin = att.pin || null;
385
                 this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
385
                 this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
386
                 break;
386
                 break;
387
+            }
387
             default:
388
             default:
388
                 this.processNode(node, from);
389
                 this.processNode(node, from);
389
             }
390
             }
391
 
392
 
392
         // Trigger status message update
393
         // Trigger status message update
393
         if (member.status) {
394
         if (member.status) {
394
-            this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
395
+            this.eventEmitter.emit(
396
+                XMPPEvents.PRESENCE_STATUS,
397
+                from,
398
+                member.status);
395
         }
399
         }
396
 
400
 
397
         if(jibri) {
401
         if(jibri) {
432
         // make sure we catch all errors coming from any handler
436
         // make sure we catch all errors coming from any handler
433
         // otherwise we can remove the presence handler from strophe
437
         // otherwise we can remove the presence handler from strophe
434
         try {
438
         try {
435
-            var tagHandler = this.presHandlers[node.tagName];
439
+            let tagHandler = this.presHandlers[node.tagName];
436
             if (node.tagName.startsWith('jitsi_participant_')) {
440
             if (node.tagName.startsWith('jitsi_participant_')) {
437
                 tagHandler = this.participantPropertyListener;
441
                 tagHandler = this.participantPropertyListener;
438
             }
442
             }
447
     }
451
     }
448
 
452
 
449
     sendMessage(body, nickname) {
453
     sendMessage(body, nickname) {
450
-        var msg = $msg({to: this.roomjid, type: 'groupchat'});
454
+        const msg = $msg({to: this.roomjid, type: 'groupchat'});
451
         msg.c('body', body).up();
455
         msg.c('body', body).up();
452
         if (nickname) {
456
         if (nickname) {
453
             msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
457
             msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
457
     }
461
     }
458
 
462
 
459
     setSubject(subject) {
463
     setSubject(subject) {
460
-        var msg = $msg({to: this.roomjid, type: 'groupchat'});
464
+        const msg = $msg({to: this.roomjid, type: 'groupchat'});
461
         msg.c('subject', subject);
465
         msg.c('subject', subject);
462
         this.connection.send(msg);
466
         this.connection.send(msg);
463
     }
467
     }
485
         // room destroyed ?
489
         // room destroyed ?
486
         if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
490
         if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
487
             + '>destroy').length) {
491
             + '>destroy').length) {
488
-            var reason;
489
-            var reasonSelect = $(pres).find(
492
+            let reason;
493
+            const reasonSelect = $(pres).find(
490
                     '>x[xmlns="http://jabber.org/protocol/muc#user"]'
494
                     '>x[xmlns="http://jabber.org/protocol/muc#user"]'
491
                     + '>destroy>reason');
495
                     + '>destroy>reason');
492
             if (reasonSelect.length) {
496
             if (reasonSelect.length) {
501
         }
505
         }
502
 
506
 
503
         // Status code 110 indicates that this notification is "self-presence".
507
         // Status code 110 indicates that this notification is "self-presence".
504
-        var isSelfPresence = $(pres).find(
508
+        const isSelfPresence = $(pres).find(
505
                 '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]'
509
                 '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]'
506
             ).length !== 0;
510
             ).length !== 0;
507
-        var isKick = $(pres).find(
511
+        const isKick = $(pres).find(
508
                 '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]'
512
                 '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]'
509
             ).length !== 0;
513
             ).length !== 0;
510
         const membersKeys = Object.keys(this.members);
514
         const membersKeys = Object.keys(this.members);
536
     }
540
     }
537
 
541
 
538
     onMessage(msg, from) {
542
     onMessage(msg, from) {
539
-        var nick
543
+        const nick
540
             = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
544
             = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
541
                 .text()
545
                 .text()
542
             || Strophe.getResourceFromJid(from);
546
             || Strophe.getResourceFromJid(from);
543
 
547
 
544
-        var txt = $(msg).find('>body').text();
545
-        var type = msg.getAttribute('type');
548
+        const txt = $(msg).find('>body').text();
549
+        const type = msg.getAttribute('type');
546
         if (type == 'error') {
550
         if (type == 'error') {
547
             this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
551
             this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
548
                 $(msg).find('>text').text(), txt);
552
                 $(msg).find('>text').text(), txt);
549
             return true;
553
             return true;
550
         }
554
         }
551
 
555
 
552
-        var subject = $(msg).find('>subject');
556
+        const subject = $(msg).find('>subject');
553
         if (subject.length) {
557
         if (subject.length) {
554
-            var subjectText = subject.text();
558
+            const subjectText = subject.text();
555
             if (subjectText || subjectText === '') {
559
             if (subjectText || subjectText === '') {
556
                 this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
560
                 this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
557
                 logger.log('Subject is changed to ' + subjectText);
561
                 logger.log('Subject is changed to ' + subjectText);
559
         }
563
         }
560
 
564
 
561
         // xep-0203 delay
565
         // xep-0203 delay
562
-        var stamp = $(msg).find('>delay').attr('stamp');
566
+        let stamp = $(msg).find('>delay').attr('stamp');
563
 
567
 
564
         if (!stamp) {
568
         if (!stamp) {
565
             // or xep-0091 delay, UTC timestamp
569
             // or xep-0091 delay, UTC timestamp
567
 
571
 
568
             if (stamp) {
572
             if (stamp) {
569
                 // the format is CCYYMMDDThh:mm:ss
573
                 // the format is CCYYMMDDThh:mm:ss
570
-                var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
574
+                const dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
571
                 stamp = dateParts[1] + '-' + dateParts[2] + '-' + dateParts[3] + 'Z';
575
                 stamp = dateParts[1] + '-' + dateParts[2] + '-' + dateParts[3] + 'Z';
572
             }
576
             }
573
         }
577
         }
589
             this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
593
             this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
590
         } else if ($(pres).find(
594
         } else if ($(pres).find(
591
             '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
595
             '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
592
-            var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
596
+            const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
593
             if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
597
             if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
594
                 // enter the room by replying with 'not-authorized'. This would
598
                 // enter the room by replying with 'not-authorized'. This would
595
                 // result in reconnection from authorized domain.
599
                 // result in reconnection from authorized domain.
612
     }
616
     }
613
 
617
 
614
     kick(jid) {
618
     kick(jid) {
615
-        var kickIQ = $iq({to: this.roomjid, type: 'set'})
619
+        const kickIQ = $iq({to: this.roomjid, type: 'set'})
616
             .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
620
             .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
617
             .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
621
             .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
618
             .c('reason').t('You have been kicked.').up().up().up();
622
             .c('reason').t('You have been kicked.').up().up().up();
629
 
633
 
630
     lockRoom(key, onSuccess, onError, onNotSupported) {
634
     lockRoom(key, onSuccess, onError, onNotSupported) {
631
         // http://xmpp.org/extensions/xep-0045.html#roomconfig
635
         // http://xmpp.org/extensions/xep-0045.html#roomconfig
632
-        var ob = this;
636
+        const ob = this;
633
         this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
637
         this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
634
             function(res) {
638
             function(res) {
635
                 if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
639
                 if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
636
-                    var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
640
+                    const formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
637
                     formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
641
                     formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
638
                     formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
642
                     formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
639
                     formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
643
                     formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
656
     }
660
     }
657
 
661
 
658
     removeFromPresence(key) {
662
     removeFromPresence(key) {
659
-        var nodes = this.presMap.nodes.filter(function(node) {
663
+        const nodes = this.presMap.nodes.filter(function(node) {
660
             return key !== node.tagName;
664
             return key !== node.tagName;
661
         });
665
         });
662
         this.presMap.nodes = nodes;
666
         this.presMap.nodes = nodes;
679
      * the MUC then <tt>null</tt> is returned.
683
      * the MUC then <tt>null</tt> is returned.
680
      */
684
      */
681
     isFocus(mucJid) {
685
     isFocus(mucJid) {
682
-        var member = this.members[mucJid];
686
+        const member = this.members[mucJid];
683
         if (member) {
687
         if (member) {
684
             return member.isFocus;
688
             return member.isFocus;
685
         }
689
         }
873
      */
877
      */
874
     muteParticipant(jid, mute) {
878
     muteParticipant(jid, mute) {
875
         logger.info('set mute', mute);
879
         logger.info('set mute', mute);
876
-        var iqToFocus = $iq(
880
+        const iqToFocus = $iq(
877
             {to: this.focusMucJid, type: 'set'})
881
             {to: this.focusMucJid, type: 'set'})
878
             .c('mute', {
882
             .c('mute', {
879
                 xmlns: 'http://jitsi.org/jitmeet/audio',
883
                 xmlns: 'http://jitsi.org/jitmeet/audio',
893
     }
897
     }
894
 
898
 
895
     onMute(iq) {
899
     onMute(iq) {
896
-        var from = iq.getAttribute('from');
900
+        const from = iq.getAttribute('from');
897
         if (from !== this.focusMucJid) {
901
         if (from !== this.focusMucJid) {
898
             logger.warn('Ignored mute from non focus peer');
902
             logger.warn('Ignored mute from non focus peer');
899
             return false;
903
             return false;
900
         }
904
         }
901
-        var mute = $(iq).find('mute');
905
+        const mute = $(iq).find('mute');
902
         if (mute.length) {
906
         if (mute.length) {
903
-            var doMuteAudio = mute.text() === 'true';
907
+            const doMuteAudio = mute.text() === 'true';
904
             this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
908
             this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
905
         }
909
         }
906
         return true;
910
         return true;

+ 67
- 67
modules/xmpp/SDP.js Visa fil

1
 /* global $, APP */
1
 /* global $, APP */
2
 
2
 
3
-var SDPUtil = require('./SDPUtil');
3
+const SDPUtil = require('./SDPUtil');
4
 
4
 
5
 // SDP STUFF
5
 // SDP STUFF
6
 function SDP(sdp) {
6
 function SDP(sdp) {
7
-    var media = sdp.split('\r\nm=');
8
-    for (var i = 1, length = media.length; i < length; i++) {
9
-        var media_i = 'm=' + media[i];
7
+    const media = sdp.split('\r\nm=');
8
+    for (let i = 1, length = media.length; i < length; i++) {
9
+        let media_i = 'm=' + media[i];
10
         if (i != length - 1) {
10
         if (i != length - 1) {
11
             media_i += '\r\n';
11
             media_i += '\r\n';
12
         }
12
         }
13
         media[i] = media_i;
13
         media[i] = media_i;
14
     }
14
     }
15
-    var session = media.shift() + '\r\n';
15
+    const session = media.shift() + '\r\n';
16
 
16
 
17
     this.media = media;
17
     this.media = media;
18
     this.raw = session + media.join('');
18
     this.raw = session + media.join('');
43
  * Returns map of MediaChannel mapped per channel idx.
43
  * Returns map of MediaChannel mapped per channel idx.
44
  */
44
  */
45
 SDP.prototype.getMediaSsrcMap = function() {
45
 SDP.prototype.getMediaSsrcMap = function() {
46
-    var self = this;
47
-    var media_ssrcs = {};
48
-    var tmp;
49
-    for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
46
+    const self = this;
47
+    const media_ssrcs = {};
48
+    let tmp;
49
+    for (let mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
50
         tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
50
         tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
51
-        var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
52
-        var media = {
51
+        const mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
52
+        const media = {
53
             mediaindex,
53
             mediaindex,
54
             mid,
54
             mid,
55
             ssrcs: {},
55
             ssrcs: {},
57
         };
57
         };
58
         media_ssrcs[mediaindex] = media;
58
         media_ssrcs[mediaindex] = media;
59
         tmp.forEach(function(line) {
59
         tmp.forEach(function(line) {
60
-            var linessrc = line.substring(7).split(' ')[0];
60
+            const linessrc = line.substring(7).split(' ')[0];
61
             // allocate new ChannelSsrc
61
             // allocate new ChannelSsrc
62
             if(!media.ssrcs[linessrc]) {
62
             if(!media.ssrcs[linessrc]) {
63
                 media.ssrcs[linessrc] = {
63
                 media.ssrcs[linessrc] = {
69
         });
69
         });
70
         tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
70
         tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
71
         tmp.forEach(function(line) {
71
         tmp.forEach(function(line) {
72
-            var idx = line.indexOf(' ');
73
-            var semantics = line.substr(0, idx).substr(13);
74
-            var ssrcs = line.substr(14 + semantics.length).split(' ');
72
+            const idx = line.indexOf(' ');
73
+            const semantics = line.substr(0, idx).substr(13);
74
+            const ssrcs = line.substr(14 + semantics.length).split(' ');
75
             if (ssrcs.length) {
75
             if (ssrcs.length) {
76
                 media.ssrcGroups.push({
76
                 media.ssrcGroups.push({
77
                     semantics,
77
                     semantics,
89
  */
89
  */
90
 SDP.prototype.containsSSRC = function(ssrc) {
90
 SDP.prototype.containsSSRC = function(ssrc) {
91
     // FIXME this code is really strange - improve it if you can
91
     // FIXME this code is really strange - improve it if you can
92
-    var medias = this.getMediaSsrcMap();
93
-    var result = false;
92
+    const medias = this.getMediaSsrcMap();
93
+    let result = false;
94
     Object.keys(medias).forEach(function(mediaindex) {
94
     Object.keys(medias).forEach(function(mediaindex) {
95
         if (result) {
95
         if (result) {
96
             return;
96
             return;
104
 
104
 
105
 // remove iSAC and CN from SDP
105
 // remove iSAC and CN from SDP
106
 SDP.prototype.mangle = function() {
106
 SDP.prototype.mangle = function() {
107
-    var i, j, lines, mline, newdesc, rtpmap;
107
+    let i, j, lines, mline, newdesc, rtpmap;
108
     for (i = 0; i < this.media.length; i++) {
108
     for (i = 0; i < this.media.length; i++) {
109
         lines = this.media[i].split('\r\n');
109
         lines = this.media[i].split('\r\n');
110
         lines.pop(); // remove empty last element
110
         lines.pop(); // remove empty last element
131
 
131
 
132
 // remove lines matching prefix from session section
132
 // remove lines matching prefix from session section
133
 SDP.prototype.removeSessionLines = function(prefix) {
133
 SDP.prototype.removeSessionLines = function(prefix) {
134
-    var self = this;
135
-    var lines = SDPUtil.find_lines(this.session, prefix);
134
+    const self = this;
135
+    const lines = SDPUtil.find_lines(this.session, prefix);
136
     lines.forEach(function(line) {
136
     lines.forEach(function(line) {
137
         self.session = self.session.replace(line + '\r\n', '');
137
         self.session = self.session.replace(line + '\r\n', '');
138
     });
138
     });
142
 // remove lines matching prefix from a media section specified by mediaindex
142
 // remove lines matching prefix from a media section specified by mediaindex
143
 // TODO: non-numeric mediaindex could match mid
143
 // TODO: non-numeric mediaindex could match mid
144
 SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
144
 SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
145
-    var self = this;
146
-    var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
145
+    const self = this;
146
+    const lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
147
     lines.forEach(function(line) {
147
     lines.forEach(function(line) {
148
         self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
148
         self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
149
     });
149
     });
153
 
153
 
154
 // add content's to a jingle element
154
 // add content's to a jingle element
155
 SDP.prototype.toJingle = function(elem, thecreator) {
155
 SDP.prototype.toJingle = function(elem, thecreator) {
156
-    var i, j, k, lines, mline, rtpmap, ssrc, tmp;
156
+    let i, j, k, lines, mline, rtpmap, ssrc, tmp;
157
     // new bundle plan
157
     // new bundle plan
158
     lines = SDPUtil.find_lines(this.session, 'a=group:');
158
     lines = SDPUtil.find_lines(this.session, 'a=group:');
159
     if (lines.length) {
159
     if (lines.length) {
160
         for (i = 0; i < lines.length; i++) {
160
         for (i = 0; i < lines.length; i++) {
161
             tmp = lines[i].split(' ');
161
             tmp = lines[i].split(' ');
162
-            var semantics = tmp.shift().substr(8);
162
+            const semantics = tmp.shift().substr(8);
163
             elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics});
163
             elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics});
164
             for (j = 0; j < tmp.length; j++) {
164
             for (j = 0; j < tmp.length; j++) {
165
                 elem.c('content', {name: tmp[j]}).up();
165
                 elem.c('content', {name: tmp[j]}).up();
174
               || mline.media === 'application')) {
174
               || mline.media === 'application')) {
175
             continue;
175
             continue;
176
         }
176
         }
177
-        var assrcline = SDPUtil.find_line(this.media[i], 'a=ssrc:');
177
+        const assrcline = SDPUtil.find_line(this.media[i], 'a=ssrc:');
178
         if (assrcline) {
178
         if (assrcline) {
179
             ssrc = assrcline.substring(7).split(' ')[0]; // take the first
179
             ssrc = assrcline.substring(7).split(' ')[0]; // take the first
180
         } else {
180
         } else {
182
         }
182
         }
183
 
183
 
184
         elem.c('content', {creator: thecreator, name: mline.media});
184
         elem.c('content', {creator: thecreator, name: mline.media});
185
-        var amidline = SDPUtil.find_line(this.media[i], 'a=mid:');
185
+        const amidline = SDPUtil.find_line(this.media[i], 'a=mid:');
186
         if (amidline) {
186
         if (amidline) {
187
             // prefer identifier from a=mid if present
187
             // prefer identifier from a=mid if present
188
-            var mid = SDPUtil.parse_mid(amidline);
188
+            const mid = SDPUtil.parse_mid(amidline);
189
             elem.attrs({ name: mid });
189
             elem.attrs({ name: mid });
190
         }
190
         }
191
 
191
 
200
                 rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
200
                 rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
201
                 elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
201
                 elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
202
                 // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
202
                 // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
203
-                var afmtpline = SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]);
203
+                const afmtpline = SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]);
204
                 if (afmtpline) {
204
                 if (afmtpline) {
205
                     tmp = SDPUtil.parse_fmtp(afmtpline);
205
                     tmp = SDPUtil.parse_fmtp(afmtpline);
206
                     for (k = 0; k < tmp.length; k++) {
206
                     for (k = 0; k < tmp.length; k++) {
211
 
211
 
212
                 elem.up();
212
                 elem.up();
213
             }
213
             }
214
-            var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
214
+            const crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
215
             if (crypto.length) {
215
             if (crypto.length) {
216
                 elem.c('encryption', {required: 1});
216
                 elem.c('encryption', {required: 1});
217
                 crypto.forEach(function(line) {
217
                 crypto.forEach(function(line) {
224
                 // new style mapping
224
                 // new style mapping
225
                 elem.c('source', { ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
225
                 elem.c('source', { ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
226
                 // FIXME: group by ssrc and support multiple different ssrcs
226
                 // FIXME: group by ssrc and support multiple different ssrcs
227
-                var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
227
+                const ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
228
                 if(ssrclines.length > 0) {
228
                 if(ssrclines.length > 0) {
229
                     ssrclines.forEach(function(line) {
229
                     ssrclines.forEach(function(line) {
230
-                        var idx = line.indexOf(' ');
231
-                        var linessrc = line.substr(0, idx).substr(7);
230
+                        const idx = line.indexOf(' ');
231
+                        const linessrc = line.substr(0, idx).substr(7);
232
                         if (linessrc != ssrc) {
232
                         if (linessrc != ssrc) {
233
                             elem.up();
233
                             elem.up();
234
                             ssrc = linessrc;
234
                             ssrc = linessrc;
235
                             elem.c('source', { ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
235
                             elem.c('source', { ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
236
                         }
236
                         }
237
-                        var kv = line.substr(idx + 1);
237
+                        const kv = line.substr(idx + 1);
238
                         elem.c('parameter');
238
                         elem.c('parameter');
239
                         if (kv.indexOf(':') == -1) {
239
                         if (kv.indexOf(':') == -1) {
240
                             elem.attrs({ name: kv });
240
                             elem.attrs({ name: kv });
241
                         } else {
241
                         } else {
242
-                            var k = kv.split(':', 2)[0];
242
+                            const k = kv.split(':', 2)[0];
243
                             elem.attrs({ name: k });
243
                             elem.attrs({ name: k });
244
 
244
 
245
-                            var v = kv.split(':', 2)[1];
245
+                            let v = kv.split(':', 2)[1];
246
                             v = SDPUtil.filter_special_chars(v);
246
                             v = SDPUtil.filter_special_chars(v);
247
                             elem.attrs({ value: v });
247
                             elem.attrs({ value: v });
248
                         }
248
                         }
279
                 elem.up();
279
                 elem.up();
280
 
280
 
281
                 // XEP-0339 handle ssrc-group attributes
281
                 // XEP-0339 handle ssrc-group attributes
282
-                var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
282
+                const ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
283
                 ssrc_group_lines.forEach(function(line) {
283
                 ssrc_group_lines.forEach(function(line) {
284
-                    var idx = line.indexOf(' ');
285
-                    var semantics = line.substr(0, idx).substr(13);
286
-                    var ssrcs = line.substr(14 + semantics.length).split(' ');
284
+                    const idx = line.indexOf(' ');
285
+                    const semantics = line.substr(0, idx).substr(13);
286
+                    const ssrcs = line.substr(14 + semantics.length).split(' ');
287
                     if (ssrcs.length) {
287
                     if (ssrcs.length) {
288
                         elem.c('ssrc-group', { semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
288
                         elem.c('ssrc-group', { semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
289
                         ssrcs.forEach(function(ssrc) {
289
                         ssrcs.forEach(function(ssrc) {
356
 };
356
 };
357
 
357
 
358
 SDP.prototype.transportToJingle = function(mediaindex, elem) {
358
 SDP.prototype.transportToJingle = function(mediaindex, elem) {
359
-    var fingerprints, sctpAttrs, sctpmap, tmp;
360
-    var self = this;
359
+    let tmp;
360
+    const self = this;
361
     elem.c('transport');
361
     elem.c('transport');
362
 
362
 
363
     // XEP-0343 DTLS/SCTP
363
     // XEP-0343 DTLS/SCTP
364
-    sctpmap
364
+    const sctpmap
365
         = SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:', self.session);
365
         = SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:', self.session);
366
     if (sctpmap) {
366
     if (sctpmap) {
367
-        sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
367
+        const sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
368
         elem.c('sctpmap', {
368
         elem.c('sctpmap', {
369
             xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
369
             xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
370
             number: sctpAttrs[0], /* SCTP port */
370
             number: sctpAttrs[0], /* SCTP port */
377
         elem.up();
377
         elem.up();
378
     }
378
     }
379
     // XEP-0320
379
     // XEP-0320
380
-    fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
380
+    const fingerprints
381
+        = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
381
     fingerprints.forEach(function(line) {
382
     fingerprints.forEach(function(line) {
382
         tmp = SDPUtil.parse_fingerprint(line);
383
         tmp = SDPUtil.parse_fingerprint(line);
383
         tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
384
         tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
396
         elem.attrs(tmp);
397
         elem.attrs(tmp);
397
         // XEP-0176
398
         // XEP-0176
398
         if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
399
         if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
399
-            var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
400
+            const lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
400
             lines.forEach(function(line) {
401
             lines.forEach(function(line) {
401
-                var candidate = SDPUtil.candidateToJingle(line);
402
+                const candidate = SDPUtil.candidateToJingle(line);
402
                 if (self.failICE) {
403
                 if (self.failICE) {
403
                     candidate.ip = '1.1.1.1';
404
                     candidate.ip = '1.1.1.1';
404
                 }
405
                 }
405
-                var protocol = candidate
406
+                const protocol = candidate
406
                         && typeof candidate.protocol === 'string'
407
                         && typeof candidate.protocol === 'string'
407
                     ? candidate.protocol.toLowerCase() : '';
408
                     ? candidate.protocol.toLowerCase() : '';
408
                 if ((self.removeTcpCandidates
409
                 if ((self.removeTcpCandidates
418
 };
419
 };
419
 
420
 
420
 SDP.prototype.rtcpFbToJingle = function(mediaindex, elem, payloadtype) { // XEP-0293
421
 SDP.prototype.rtcpFbToJingle = function(mediaindex, elem, payloadtype) { // XEP-0293
421
-    var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
422
+    const lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
422
     lines.forEach(function(line) {
423
     lines.forEach(function(line) {
423
-        var tmp = SDPUtil.parse_rtcpfb(line);
424
+        const tmp = SDPUtil.parse_rtcpfb(line);
424
         if (tmp.type == 'trr-int') {
425
         if (tmp.type == 'trr-int') {
425
             elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
426
             elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
426
             elem.up();
427
             elem.up();
435
 };
436
 };
436
 
437
 
437
 SDP.prototype.rtcpFbFromJingle = function(elem, payloadtype) { // XEP-0293
438
 SDP.prototype.rtcpFbFromJingle = function(elem, payloadtype) { // XEP-0293
438
-    var media = '';
439
-    var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
439
+    let media = '';
440
+    let tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
440
     if (tmp.length) {
441
     if (tmp.length) {
441
         media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
442
         media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
442
         if (tmp.attr('value')) {
443
         if (tmp.attr('value')) {
459
 
460
 
460
 // construct an SDP from a jingle stanza
461
 // construct an SDP from a jingle stanza
461
 SDP.prototype.fromJingle = function(jingle) {
462
 SDP.prototype.fromJingle = function(jingle) {
462
-    var self = this;
463
+    const self = this;
463
     this.raw = 'v=0\r\n'
464
     this.raw = 'v=0\r\n'
464
         + 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n'// FIXME
465
         + 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n'// FIXME
465
         + 's=-\r\n'
466
         + 's=-\r\n'
467
     // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
468
     // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
468
     if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
469
     if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
469
         $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function(idx, group) {
470
         $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function(idx, group) {
470
-            var contents = $(group).find('>content').map(function(idx, content) {
471
+            const contents = $(group).find('>content').map(function(idx, content) {
471
                 return content.getAttribute('name');
472
                 return content.getAttribute('name');
472
             }).get();
473
             }).get();
473
             if (contents.length > 0) {
474
             if (contents.length > 0) {
478
 
479
 
479
     this.session = this.raw;
480
     this.session = this.raw;
480
     jingle.find('>content').each(function() {
481
     jingle.find('>content').each(function() {
481
-        var m = self.jingle2media($(this));
482
+        const m = self.jingle2media($(this));
482
         self.media.push(m);
483
         self.media.push(m);
483
     });
484
     });
484
 
485
 
495
 
496
 
496
 // translate a jingle content element into an an SDP media part
497
 // translate a jingle content element into an an SDP media part
497
 SDP.prototype.jingle2media = function(content) {
498
 SDP.prototype.jingle2media = function(content) {
498
-    var desc = content.find('description'),
499
-        media = '',
500
-        self = this,
501
-        tmp;
502
-    var sctp = content.find(
499
+    const desc = content.find('description');
500
+    let media = '';
501
+    const self = this;
502
+    const sctp = content.find(
503
         '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
503
         '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
504
 
504
 
505
-    tmp = { media: desc.attr('media') };
505
+    let tmp = { media: desc.attr('media') };
506
     tmp.port = '1';
506
     tmp.port = '1';
507
     if (content.attr('senders') == 'rejected') {
507
     if (content.attr('senders') == 'rejected') {
508
         // estos hack to reject an m-line.
508
         // estos hack to reject an m-line.
525
         media += 'a=sctpmap:' + sctp.attr('number')
525
         media += 'a=sctpmap:' + sctp.attr('number')
526
             + ' ' + sctp.attr('protocol');
526
             + ' ' + sctp.attr('protocol');
527
 
527
 
528
-        var streamCount = sctp.attr('streams');
528
+        const streamCount = sctp.attr('streams');
529
         if (streamCount) {
529
         if (streamCount) {
530
             media += ' ' + streamCount + '\r\n';
530
             media += ' ' + streamCount + '\r\n';
531
         } else {
531
         } else {
614
     });
614
     });
615
 
615
 
616
     content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function() {
616
     content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function() {
617
-        var protocol = this.getAttribute('protocol');
617
+        let protocol = this.getAttribute('protocol');
618
         protocol = typeof protocol === 'string' ? protocol.toLowerCase() : '';
618
         protocol = typeof protocol === 'string' ? protocol.toLowerCase() : '';
619
 
619
 
620
         if ((self.removeTcpCandidates
620
         if ((self.removeTcpCandidates
630
 
630
 
631
     // XEP-0339 handle ssrc-group attributes
631
     // XEP-0339 handle ssrc-group attributes
632
     content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
632
     content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
633
-        var semantics = this.getAttribute('semantics');
634
-        var ssrcs = $(this).find('>source').map(function() {
633
+        const semantics = this.getAttribute('semantics');
634
+        const ssrcs = $(this).find('>source').map(function() {
635
             return this.getAttribute('ssrc');
635
             return this.getAttribute('ssrc');
636
         }).get();
636
         }).get();
637
 
637
 
642
 
642
 
643
     tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
643
     tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
644
     tmp.each(function() {
644
     tmp.each(function() {
645
-        var ssrc = this.getAttribute('ssrc');
645
+        const ssrc = this.getAttribute('ssrc');
646
         $(this).find('>parameter').each(function() {
646
         $(this).find('>parameter').each(function() {
647
-            var name = this.getAttribute('name');
648
-            var value = this.getAttribute('value');
647
+            const name = this.getAttribute('name');
648
+            let value = this.getAttribute('value');
649
             value = SDPUtil.filter_special_chars(value);
649
             value = SDPUtil.filter_special_chars(value);
650
             media += 'a=ssrc:' + ssrc + ' ' + name;
650
             media += 'a=ssrc:' + ssrc + ' ' + name;
651
             if (value && value.length) {
651
             if (value && value.length) {

+ 19
- 19
modules/xmpp/SDPDiffer.js Visa fil

1
-var SDPUtil = require('./SDPUtil');
1
+const SDPUtil = require('./SDPUtil');
2
 
2
 
3
 function SDPDiffer(mySDP, otherSDP) {
3
 function SDPDiffer(mySDP, otherSDP) {
4
     this.mySDP = mySDP;
4
     this.mySDP = mySDP;
23
             return false;
23
             return false;
24
         }
24
         }
25
 
25
 
26
-        for (var i = 0, l = this.length; i < l; i++) {
26
+        for (let i = 0, l = this.length; i < l; i++) {
27
             // Check if we have nested arrays
27
             // Check if we have nested arrays
28
             if (this[i] instanceof Array && array[i] instanceof Array) {
28
             if (this[i] instanceof Array && array[i] instanceof Array) {
29
                 // recurse into the nested arrays
29
                 // recurse into the nested arrays
39
         return true;
39
         return true;
40
     }
40
     }
41
 
41
 
42
-    var myMedias = this.mySDP.getMediaSsrcMap();
43
-    var othersMedias = this.otherSDP.getMediaSsrcMap();
44
-    var newMedia = {};
42
+    const myMedias = this.mySDP.getMediaSsrcMap();
43
+    const othersMedias = this.otherSDP.getMediaSsrcMap();
44
+    const newMedia = {};
45
     Object.keys(othersMedias).forEach(function(othersMediaIdx) {
45
     Object.keys(othersMedias).forEach(function(othersMediaIdx) {
46
-        var myMedia = myMedias[othersMediaIdx];
47
-        var othersMedia = othersMedias[othersMediaIdx];
46
+        const myMedia = myMedias[othersMediaIdx];
47
+        const othersMedia = othersMedias[othersMediaIdx];
48
         if(!myMedia && othersMedia) {
48
         if(!myMedia && othersMedia) {
49
             // Add whole channel
49
             // Add whole channel
50
             newMedia[othersMediaIdx] = othersMedia;
50
             newMedia[othersMediaIdx] = othersMedia;
71
         othersMedia.ssrcGroups.forEach(function(otherSsrcGroup) {
71
         othersMedia.ssrcGroups.forEach(function(otherSsrcGroup) {
72
 
72
 
73
             // try to match the other ssrc-group with an ssrc-group of ours
73
             // try to match the other ssrc-group with an ssrc-group of ours
74
-            var matched = false;
75
-            for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
76
-                var mySsrcGroup = myMedia.ssrcGroups[i];
74
+            let matched = false;
75
+            for (let i = 0; i < myMedia.ssrcGroups.length; i++) {
76
+                const mySsrcGroup = myMedia.ssrcGroups[i];
77
                 if (otherSsrcGroup.semantics == mySsrcGroup.semantics
77
                 if (otherSsrcGroup.semantics == mySsrcGroup.semantics
78
                     && arrayEquals.apply(otherSsrcGroup.ssrcs,
78
                     && arrayEquals.apply(otherSsrcGroup.ssrcs,
79
                                       [mySsrcGroup.ssrcs])) {
79
                                       [mySsrcGroup.ssrcs])) {
106
  * TODO: document!
106
  * TODO: document!
107
  */
107
  */
108
 SDPDiffer.prototype.toJingle = function(modify) {
108
 SDPDiffer.prototype.toJingle = function(modify) {
109
-    var sdpMediaSsrcs = this.getNewMedia();
109
+    const sdpMediaSsrcs = this.getNewMedia();
110
 
110
 
111
-    var modified = false;
111
+    let modified = false;
112
     Object.keys(sdpMediaSsrcs).forEach(function(mediaindex) {
112
     Object.keys(sdpMediaSsrcs).forEach(function(mediaindex) {
113
         modified = true;
113
         modified = true;
114
-        var media = sdpMediaSsrcs[mediaindex];
114
+        const media = sdpMediaSsrcs[mediaindex];
115
         modify.c('content', {name: media.mid});
115
         modify.c('content', {name: media.mid});
116
 
116
 
117
         modify.c('description',
117
         modify.c('description',
120
         // different ssrcs correctly
120
         // different ssrcs correctly
121
         // generate sources from lines
121
         // generate sources from lines
122
         Object.keys(media.ssrcs).forEach(function(ssrcNum) {
122
         Object.keys(media.ssrcs).forEach(function(ssrcNum) {
123
-            var mediaSsrc = media.ssrcs[ssrcNum];
123
+            const mediaSsrc = media.ssrcs[ssrcNum];
124
             modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
124
             modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
125
             modify.attrs({ssrc: mediaSsrc.ssrc});
125
             modify.attrs({ssrc: mediaSsrc.ssrc});
126
             // iterate over ssrc lines
126
             // iterate over ssrc lines
127
             mediaSsrc.lines.forEach(function(line) {
127
             mediaSsrc.lines.forEach(function(line) {
128
-                var idx = line.indexOf(' ');
129
-                var kv = line.substr(idx + 1);
128
+                const idx = line.indexOf(' ');
129
+                const kv = line.substr(idx + 1);
130
                 modify.c('parameter');
130
                 modify.c('parameter');
131
                 if (kv.indexOf(':') == -1) {
131
                 if (kv.indexOf(':') == -1) {
132
                     modify.attrs({ name: kv });
132
                     modify.attrs({ name: kv });
133
                 } else {
133
                 } else {
134
-                    var nv = kv.split(':', 2);
135
-                    var name = nv[0];
136
-                    var value = SDPUtil.filter_special_chars(nv[1]);
134
+                    const nv = kv.split(':', 2);
135
+                    const name = nv[0];
136
+                    const value = SDPUtil.filter_special_chars(nv[1]);
137
                     modify.attrs({ name });
137
                     modify.attrs({ name });
138
                     modify.attrs({ value });
138
                     modify.attrs({ value });
139
                 }
139
                 }

+ 55
- 50
modules/xmpp/SDPUtil.js Visa fil

1
 import {getLogger} from 'jitsi-meet-logger';
1
 import {getLogger} from 'jitsi-meet-logger';
2
 const logger = getLogger(__filename);
2
 const logger = getLogger(__filename);
3
 import RandomUtil from '../util/RandomUtil';
3
 import RandomUtil from '../util/RandomUtil';
4
-var RTCBrowserType = require('../RTC/RTCBrowserType');
4
+const RTCBrowserType = require('../RTC/RTCBrowserType');
5
 
5
 
6
-var SDPUtil = {
6
+const SDPUtil = {
7
     filter_special_chars(text) {
7
     filter_special_chars(text) {
8
         // XXX Neither one of the falsy values (e.g. null, undefined, false,
8
         // XXX Neither one of the falsy values (e.g. null, undefined, false,
9
         // "", etc.) "contain" special chars.
9
         // "", etc.) "contain" special chars.
10
         return text ? text.replace(/[\\\/\{,\}\+]/g, '') : text;
10
         return text ? text.replace(/[\\\/\{,\}\+]/g, '') : text;
11
     },
11
     },
12
     iceparams(mediadesc, sessiondesc) {
12
     iceparams(mediadesc, sessiondesc) {
13
-        var data = null;
14
-        var pwd, ufrag;
13
+        let data = null;
14
+        let pwd, ufrag;
15
         if ((ufrag = SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc))
15
         if ((ufrag = SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc))
16
                 && (pwd = SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))) {
16
                 && (pwd = SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))) {
17
             data = {
17
             data = {
37
         return line.substring(6);
37
         return line.substring(6);
38
     },
38
     },
39
     parse_mline(line) {
39
     parse_mline(line) {
40
-        var data = {},
41
-            parts = line.substring(2).split(' ');
40
+        const data = {};
41
+        const parts = line.substring(2).split(' ');
42
+
42
         data.media = parts.shift();
43
         data.media = parts.shift();
43
         data.port = parts.shift();
44
         data.port = parts.shift();
44
         data.proto = parts.shift();
45
         data.proto = parts.shift();
52
         return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
53
         return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
53
     },
54
     },
54
     parse_rtpmap(line) {
55
     parse_rtpmap(line) {
55
-        var data = {},
56
-            parts = line.substring(9).split(' ');
56
+        const data = {};
57
+        let parts = line.substring(9).split(' ');
58
+
57
         data.id = parts.shift();
59
         data.id = parts.shift();
58
         parts = parts[0].split('/');
60
         parts = parts[0].split('/');
59
         data.name = parts.shift();
61
         data.name = parts.shift();
67
      * @returns [SCTP port number, protocol, streams]
69
      * @returns [SCTP port number, protocol, streams]
68
      */
70
      */
69
     parse_sctpmap(line) {
71
     parse_sctpmap(line) {
70
-        var parts = line.substring(10).split(' ');
71
-        var sctpPort = parts[0];
72
-        var protocol = parts[1];
72
+        const parts = line.substring(10).split(' ');
73
+        const sctpPort = parts[0];
74
+        const protocol = parts[1];
73
         // Stream count is optional
75
         // Stream count is optional
74
-        var streamCount = parts.length > 2 ? parts[2] : null;
76
+        const streamCount = parts.length > 2 ? parts[2] : null;
75
         return [sctpPort, protocol, streamCount];// SCTP port
77
         return [sctpPort, protocol, streamCount];// SCTP port
76
     },
78
     },
77
     build_rtpmap(el) {
79
     build_rtpmap(el) {
78
-        var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
80
+        let line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
79
         if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
81
         if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
80
             line += '/' + el.getAttribute('channels');
82
             line += '/' + el.getAttribute('channels');
81
         }
83
         }
82
         return line;
84
         return line;
83
     },
85
     },
84
     parse_crypto(line) {
86
     parse_crypto(line) {
85
-        var data = {},
86
-            parts = line.substring(9).split(' ');
87
+        const data = {};
88
+        const parts = line.substring(9).split(' ');
89
+
87
         data.tag = parts.shift();
90
         data.tag = parts.shift();
88
         data['crypto-suite'] = parts.shift();
91
         data['crypto-suite'] = parts.shift();
89
         data['key-params'] = parts.shift();
92
         data['key-params'] = parts.shift();
93
         return data;
96
         return data;
94
     },
97
     },
95
     parse_fingerprint(line) { // RFC 4572
98
     parse_fingerprint(line) { // RFC 4572
96
-        var data = {},
97
-            parts = line.substring(14).split(' ');
99
+        const data = {};
100
+        const parts = line.substring(14).split(' ');
101
+
98
         data.hash = parts.shift();
102
         data.hash = parts.shift();
99
         data.fingerprint = parts.shift();
103
         data.fingerprint = parts.shift();
100
         // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
104
         // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
101
         return data;
105
         return data;
102
     },
106
     },
103
     parse_fmtp(line) {
107
     parse_fmtp(line) {
104
-        var data = [],
105
-            i,
106
-            key,
107
-            parts = line.split(' '),
108
-            value;
108
+        const data = [];
109
+        let parts = line.split(' ');
110
+
109
         parts.shift();
111
         parts.shift();
110
         parts = parts.join(' ').split(';');
112
         parts = parts.join(' ').split(';');
111
-        for (i = 0; i < parts.length; i++) {
112
-            key = parts[i].split('=')[0];
113
+        for (let i = 0; i < parts.length; i++) {
114
+            let key = parts[i].split('=')[0];
113
             while (key.length && key[0] == ' ') {
115
             while (key.length && key[0] == ' ') {
114
                 key = key.substring(1);
116
                 key = key.substring(1);
115
             }
117
             }
116
-            value = parts[i].split('=')[1];
118
+            const value = parts[i].split('=')[1];
117
             if (key && value) {
119
             if (key && value) {
118
                 data.push({name: key, value});
120
                 data.push({name: key, value});
119
             } else if (key) {
121
             } else if (key) {
124
         return data;
126
         return data;
125
     },
127
     },
126
     parse_icecandidate(line) {
128
     parse_icecandidate(line) {
127
-        var candidate = {},
128
-            elems = line.split(' ');
129
+        const candidate = {};
130
+        const elems = line.split(' ');
131
+
129
         candidate.foundation = elems[0].substring(12);
132
         candidate.foundation = elems[0].substring(12);
130
         candidate.component = elems[1];
133
         candidate.component = elems[1];
131
         candidate.protocol = elems[2].toLowerCase();
134
         candidate.protocol = elems[2].toLowerCase();
135
         // elems[6] => "typ"
138
         // elems[6] => "typ"
136
         candidate.type = elems[7];
139
         candidate.type = elems[7];
137
         candidate.generation = 0; // default value, may be overwritten below
140
         candidate.generation = 0; // default value, may be overwritten below
138
-        for (var i = 8; i < elems.length; i += 2) {
141
+        for (let i = 8; i < elems.length; i += 2) {
139
             switch (elems[i]) {
142
             switch (elems[i]) {
140
             case 'raddr':
143
             case 'raddr':
141
                 candidate['rel-addr'] = elems[i + 1];
144
                 candidate['rel-addr'] = elems[i + 1];
158
         return candidate;
161
         return candidate;
159
     },
162
     },
160
     build_icecandidate(cand) {
163
     build_icecandidate(cand) {
161
-        var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
164
+        let line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
162
         line += ' ';
165
         line += ' ';
163
         switch (cand.type) {
166
         switch (cand.type) {
164
         case 'srflx':
167
         case 'srflx':
191
         // proprietary mapping of a=ssrc lines
194
         // proprietary mapping of a=ssrc lines
192
         // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
195
         // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
193
         // and parse according to that
196
         // and parse according to that
194
-        var data = {},
195
-            lines = desc.split('\r\n');
196
-        for (var i = 0; i < lines.length; i++) {
197
+        const data = {};
198
+        const lines = desc.split('\r\n');
199
+
200
+        for (let i = 0; i < lines.length; i++) {
197
             if (lines[i].substring(0, 7) == 'a=ssrc:') {
201
             if (lines[i].substring(0, 7) == 'a=ssrc:') {
198
-                var idx = lines[i].indexOf(' ');
202
+                const idx = lines[i].indexOf(' ');
199
                 data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
203
                 data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
200
             }
204
             }
201
         }
205
         }
202
         return data;
206
         return data;
203
     },
207
     },
204
     parse_rtcpfb(line) {
208
     parse_rtcpfb(line) {
205
-        var parts = line.substr(10).split(' ');
206
-        var data = {};
209
+        const parts = line.substr(10).split(' ');
210
+        const data = {};
207
         data.pt = parts.shift();
211
         data.pt = parts.shift();
208
         data.type = parts.shift();
212
         data.type = parts.shift();
209
         data.params = parts;
213
         data.params = parts;
210
         return data;
214
         return data;
211
     },
215
     },
212
     parse_extmap(line) {
216
     parse_extmap(line) {
213
-        var parts = line.substr(9).split(' ');
214
-        var data = {};
217
+        const parts = line.substr(9).split(' ');
218
+        const data = {};
215
         data.value = parts.shift();
219
         data.value = parts.shift();
216
         if (data.value.indexOf('/') != -1) {
220
         if (data.value.indexOf('/') != -1) {
217
             data.direction = data.value.substr(data.value.indexOf('/') + 1);
221
             data.direction = data.value.substr(data.value.indexOf('/') + 1);
224
         return data;
228
         return data;
225
     },
229
     },
226
     find_line(haystack, needle, sessionpart) {
230
     find_line(haystack, needle, sessionpart) {
227
-        var lines = haystack.split('\r\n');
228
-        for (var i = 0; i < lines.length; i++) {
231
+        let lines = haystack.split('\r\n');
232
+        for (let i = 0; i < lines.length; i++) {
229
             if (lines[i].substring(0, needle.length) == needle) {
233
             if (lines[i].substring(0, needle.length) == needle) {
230
                 return lines[i];
234
                 return lines[i];
231
             }
235
             }
235
         }
239
         }
236
         // search session part
240
         // search session part
237
         lines = sessionpart.split('\r\n');
241
         lines = sessionpart.split('\r\n');
238
-        for (var j = 0; j < lines.length; j++) {
242
+        for (let j = 0; j < lines.length; j++) {
239
             if (lines[j].substring(0, needle.length) == needle) {
243
             if (lines[j].substring(0, needle.length) == needle) {
240
                 return lines[j];
244
                 return lines[j];
241
             }
245
             }
243
         return false;
247
         return false;
244
     },
248
     },
245
     find_lines(haystack, needle, sessionpart) {
249
     find_lines(haystack, needle, sessionpart) {
246
-        var lines = haystack.split('\r\n'),
247
-            needles = [];
248
-        for (var i = 0; i < lines.length; i++) {
250
+        let lines = haystack.split('\r\n');
251
+        const needles = [];
252
+
253
+        for (let i = 0; i < lines.length; i++) {
249
             if (lines[i].substring(0, needle.length) == needle) {
254
             if (lines[i].substring(0, needle.length) == needle) {
250
                 needles.push(lines[i]);
255
                 needles.push(lines[i]);
251
             }
256
             }
255
         }
260
         }
256
         // search session part
261
         // search session part
257
         lines = sessionpart.split('\r\n');
262
         lines = sessionpart.split('\r\n');
258
-        for (var j = 0; j < lines.length; j++) {
263
+        for (let j = 0; j < lines.length; j++) {
259
             if (lines[j].substring(0, needle.length) == needle) {
264
             if (lines[j].substring(0, needle.length) == needle) {
260
                 needles.push(lines[j]);
265
                 needles.push(lines[j]);
261
             }
266
             }
275
         if (line.substring(line.length - 2) == '\r\n') {// chomp it
280
         if (line.substring(line.length - 2) == '\r\n') {// chomp it
276
             line = line.substring(0, line.length - 2);
281
             line = line.substring(0, line.length - 2);
277
         }
282
         }
278
-        var candidate = {},
279
-            elems = line.split(' '),
280
-            i;
283
+        const candidate = {};
284
+        const elems = line.split(' ');
285
+
281
         if (elems[6] != 'typ') {
286
         if (elems[6] != 'typ') {
282
             logger.log('did not find typ in the right place');
287
             logger.log('did not find typ in the right place');
283
             logger.log(line);
288
             logger.log(line);
293
         candidate.type = elems[7];
298
         candidate.type = elems[7];
294
 
299
 
295
         candidate.generation = '0'; // default, may be overwritten below
300
         candidate.generation = '0'; // default, may be overwritten below
296
-        for (i = 8; i < elems.length; i += 2) {
301
+        for (let i = 8; i < elems.length; i += 2) {
297
             switch (elems[i]) {
302
             switch (elems[i]) {
298
             case 'raddr':
303
             case 'raddr':
299
                 candidate['rel-addr'] = elems[i + 1];
304
                 candidate['rel-addr'] = elems[i + 1];
316
         return candidate;
321
         return candidate;
317
     },
322
     },
318
     candidateFromJingle(cand) {
323
     candidateFromJingle(cand) {
319
-        var line = 'a=candidate:';
324
+        let line = 'a=candidate:';
320
         line += cand.getAttribute('foundation');
325
         line += cand.getAttribute('foundation');
321
         line += ' ';
326
         line += ' ';
322
         line += cand.getAttribute('component');
327
         line += cand.getAttribute('component');
323
         line += ' ';
328
         line += ' ';
324
 
329
 
325
-        var protocol = cand.getAttribute('protocol');
330
+        let protocol = cand.getAttribute('protocol');
326
         // use tcp candidates for FF
331
         // use tcp candidates for FF
327
         if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
332
         if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
328
             protocol = 'tcp';
333
             protocol = 'tcp';

+ 34
- 34
modules/xmpp/moderator.js Visa fil

1
 /* global $, $iq, Promise, Strophe */
1
 /* global $, $iq, Promise, Strophe */
2
 
2
 
3
-var logger = require('jitsi-meet-logger').getLogger(__filename);
4
-var XMPPEvents = require('../../service/xmpp/XMPPEvents');
5
-var AuthenticationEvents
3
+const logger = require('jitsi-meet-logger').getLogger(__filename);
4
+const XMPPEvents = require('../../service/xmpp/XMPPEvents');
5
+const AuthenticationEvents
6
     = require('../../service/authentication/AuthenticationEvents');
6
     = require('../../service/authentication/AuthenticationEvents');
7
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
7
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
8
 import Settings from '../settings/Settings';
8
 import Settings from '../settings/Settings';
9
 
9
 
10
 function createExpBackoffTimer(step) {
10
 function createExpBackoffTimer(step) {
11
-    var count = 1;
11
+    let count = 1;
12
     return function(reset) {
12
     return function(reset) {
13
         // Reset call
13
         // Reset call
14
         if (reset) {
14
         if (reset) {
16
             return;
16
             return;
17
         }
17
         }
18
         // Calculate next timeout
18
         // Calculate next timeout
19
-        var timeout = Math.pow(2, count - 1);
19
+        const timeout = Math.pow(2, count - 1);
20
         count += 1;
20
         count += 1;
21
         return timeout * step;
21
         return timeout * step;
22
     };
22
     };
73
 
73
 
74
 Moderator.prototype.onMucMemberLeft = function(jid) {
74
 Moderator.prototype.onMucMemberLeft = function(jid) {
75
     logger.info('Someone left is it focus ? ' + jid);
75
     logger.info('Someone left is it focus ? ' + jid);
76
-    var resource = Strophe.getResourceFromJid(jid);
76
+    const resource = Strophe.getResourceFromJid(jid);
77
     if (resource === 'focus') {
77
     if (resource === 'focus') {
78
         logger.info(
78
         logger.info(
79
             'Focus has left the room - leaving conference');
79
             'Focus has left the room - leaving conference');
96
 
96
 
97
 Moderator.prototype.getFocusComponent = function() {
97
 Moderator.prototype.getFocusComponent = function() {
98
     // Get focus component address
98
     // Get focus component address
99
-    var focusComponent = this.options.connection.hosts.focus;
99
+    let focusComponent = this.options.connection.hosts.focus;
100
     // If not specified use default:  'focus.domain'
100
     // If not specified use default:  'focus.domain'
101
     if (!focusComponent) {
101
     if (!focusComponent) {
102
         focusComponent = 'focus.' + this.options.connection.hosts.domain;
102
         focusComponent = 'focus.' + this.options.connection.hosts.domain;
106
 
106
 
107
 Moderator.prototype.createConferenceIq = function() {
107
 Moderator.prototype.createConferenceIq = function() {
108
     // Generate create conference IQ
108
     // Generate create conference IQ
109
-    var elem = $iq({to: this.getFocusComponent(), type: 'set'});
109
+    const elem = $iq({to: this.getFocusComponent(), type: 'set'});
110
 
110
 
111
     // Session Id used for authentication
111
     // Session Id used for authentication
112
-    var sessionId = Settings.getSessionId();
113
-    var machineUID = Settings.getMachineId();
112
+    const sessionId = Settings.getSessionId();
113
+    const machineUID = Settings.getMachineId();
114
 
114
 
115
     logger.info(
115
     logger.info(
116
             'Session ID: ' + sessionId + ' machine UID: ' + machineUID);
116
             'Session ID: ' + sessionId + ' machine UID: ' + machineUID);
219
 
219
 
220
 
220
 
221
 Moderator.prototype.parseSessionId = function(resultIq) {
221
 Moderator.prototype.parseSessionId = function(resultIq) {
222
-    var sessionId = $(resultIq).find('conference').attr('session-id');
222
+    const sessionId = $(resultIq).find('conference').attr('session-id');
223
     if (sessionId) {
223
     if (sessionId) {
224
         logger.info('Received sessionId:  ' + sessionId);
224
         logger.info('Received sessionId:  ' + sessionId);
225
         Settings.setSessionId(sessionId);
225
         Settings.setSessionId(sessionId);
231
     this.setFocusUserJid(
231
     this.setFocusUserJid(
232
         $(resultIq).find('conference').attr('focusjid'));
232
         $(resultIq).find('conference').attr('focusjid'));
233
 
233
 
234
-    var authenticationEnabled
234
+    const authenticationEnabled
235
         = $(resultIq).find(
235
         = $(resultIq).find(
236
             '>conference>property'
236
             '>conference>property'
237
             + '[name=\'authentication\'][value=\'true\']').length > 0;
237
             + '[name=\'authentication\'][value=\'true\']').length > 0;
250
         this.parseSessionId(resultIq);
250
         this.parseSessionId(resultIq);
251
     }
251
     }
252
 
252
 
253
-    var authIdentity = $(resultIq).find('>conference').attr('identity');
253
+    const authIdentity = $(resultIq).find('>conference').attr('identity');
254
 
254
 
255
     this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
255
     this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
256
         authenticationEnabled, authIdentity);
256
         authenticationEnabled, authIdentity);
301
 Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
301
 Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
302
     // If the session is invalid, remove and try again without session ID to get
302
     // If the session is invalid, remove and try again without session ID to get
303
     // a new one
303
     // a new one
304
-    var invalidSession = $(error).find('>error>session-invalid').length;
304
+    const invalidSession = $(error).find('>error>session-invalid').length;
305
     if (invalidSession) {
305
     if (invalidSession) {
306
         logger.info('Session expired! - removing');
306
         logger.info('Session expired! - removing');
307
         Settings.clearSessionId();
307
         Settings.clearSessionId();
311
         return;
311
         return;
312
     }
312
     }
313
     // Check for error returned by the reservation system
313
     // Check for error returned by the reservation system
314
-    var reservationErr = $(error).find('>error>reservation-error');
314
+    const reservationErr = $(error).find('>error>reservation-error');
315
     if (reservationErr.length) {
315
     if (reservationErr.length) {
316
         // Trigger error event
316
         // Trigger error event
317
-        var errorCode = reservationErr.attr('error-code');
318
-        var errorTextNode = $(error).find('>error>text');
319
-        var errorMsg;
317
+        const errorCode = reservationErr.attr('error-code');
318
+        const errorTextNode = $(error).find('>error>text');
319
+        let errorMsg;
320
         if (errorTextNode) {
320
         if (errorTextNode) {
321
             errorMsg = errorTextNode.text();
321
             errorMsg = errorTextNode.text();
322
         }
322
         }
327
     // Not authorized to create new room
327
     // Not authorized to create new room
328
     if ($(error).find('>error>not-authorized').length) {
328
     if ($(error).find('>error>not-authorized').length) {
329
         logger.warn('Unauthorized to start the conference', error);
329
         logger.warn('Unauthorized to start the conference', error);
330
-        var toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
330
+        const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
331
         if (toDomain !== this.options.connection.hosts.anonymousdomain) {
331
         if (toDomain !== this.options.connection.hosts.anonymousdomain) {
332
             // FIXME "is external" should come either from the focus or
332
             // FIXME "is external" should come either from the focus or
333
             // config.js
333
             // config.js
336
         this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
336
         this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
337
         return;
337
         return;
338
     }
338
     }
339
-    var waitMs = this.getNextErrorTimeout();
340
-    var errmsg = 'Focus error, retry after ' + waitMs;
339
+    const waitMs = this.getNextErrorTimeout();
340
+    const errmsg = 'Focus error, retry after ' + waitMs;
341
     GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
341
     GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
342
     logger.error(errmsg, error);
342
     logger.error(errmsg, error);
343
     // Show message
343
     // Show message
344
-    var focusComponent = this.getFocusComponent();
345
-    var retrySec = waitMs / 1000;
344
+    const focusComponent = this.getFocusComponent();
345
+    const retrySec = waitMs / 1000;
346
     // FIXME: message is duplicated ? Do not show in case of session invalid
346
     // FIXME: message is duplicated ? Do not show in case of session invalid
347
     // which means just a retry
347
     // which means just a retry
348
     if (!invalidSession) {
348
     if (!invalidSession) {
377
         // Exec callback
377
         // Exec callback
378
         callback();
378
         callback();
379
     } else {
379
     } else {
380
-        var waitMs = this.getNextTimeout();
380
+        const waitMs = this.getNextTimeout();
381
         logger.info('Waiting for the focus... ' + waitMs);
381
         logger.info('Waiting for the focus... ' + waitMs);
382
         window.setTimeout(() => this.allocateConferenceFocus(callback),
382
         window.setTimeout(() => this.allocateConferenceFocus(callback),
383
             waitMs);
383
             waitMs);
392
                 this.parseSessionId(result);
392
                 this.parseSessionId(result);
393
                 resolve();
393
                 resolve();
394
             }, error => {
394
             }, error => {
395
-                var code = $(error).find('>error').attr('code');
395
+                const code = $(error).find('>error').attr('code');
396
                 reject(error, code);
396
                 reject(error, code);
397
             }
397
             }
398
         );
398
         );
411
  * @param failureCb
411
  * @param failureCb
412
  */
412
  */
413
 Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
413
 Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
414
-    var iq = $iq({to: this.getFocusComponent(), type: 'get'});
415
-    var attrs = {
414
+    const iq = $iq({to: this.getFocusComponent(), type: 'get'});
415
+    const attrs = {
416
         xmlns: 'http://jitsi.org/protocol/focus',
416
         xmlns: 'http://jitsi.org/protocol/focus',
417
         room: this.roomName,
417
         room: this.roomName,
418
         'machine-uid': Settings.getMachineId()
418
         'machine-uid': Settings.getMachineId()
419
     };
419
     };
420
-    var str = 'auth url'; // for logger
420
+    let str = 'auth url'; // for logger
421
     if (popup) {
421
     if (popup) {
422
         attrs.popup = true;
422
         attrs.popup = true;
423
         str = 'POPUP ' + str;
423
         str = 'POPUP ' + str;
438
     this.connection.sendIQ(
438
     this.connection.sendIQ(
439
         iq,
439
         iq,
440
         function(result) {
440
         function(result) {
441
-            var url = $(result).find('login-url').attr('url');
441
+            let url = $(result).find('login-url').attr('url');
442
             url = decodeURIComponent(url);
442
             url = decodeURIComponent(url);
443
             if (url) {
443
             if (url) {
444
                 logger.info('Got ' + str + ': ' + url);
444
                 logger.info('Got ' + str + ': ' + url);
456
 };
456
 };
457
 
457
 
458
 Moderator.prototype.logout = function(callback) {
458
 Moderator.prototype.logout = function(callback) {
459
-    var iq = $iq({to: this.getFocusComponent(), type: 'set'});
460
-    var sessionId = Settings.getSessionId();
459
+    const iq = $iq({to: this.getFocusComponent(), type: 'set'});
460
+    const sessionId = Settings.getSessionId();
461
     if (!sessionId) {
461
     if (!sessionId) {
462
         callback();
462
         callback();
463
         return;
463
         return;
469
     this.connection.sendIQ(
469
     this.connection.sendIQ(
470
         iq,
470
         iq,
471
         function(result) {
471
         function(result) {
472
-            var logoutUrl = $(result).find('logout').attr('logout-url');
472
+            let logoutUrl = $(result).find('logout').attr('logout-url');
473
             if (logoutUrl) {
473
             if (logoutUrl) {
474
                 logoutUrl = decodeURIComponent(logoutUrl);
474
                 logoutUrl = decodeURIComponent(logoutUrl);
475
             }
475
             }
478
             callback(logoutUrl);
478
             callback(logoutUrl);
479
         }.bind(this),
479
         }.bind(this),
480
         function(error) {
480
         function(error) {
481
-            var errmsg = 'Logout error';
481
+            const errmsg = 'Logout error';
482
             GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
482
             GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
483
             logger.error(errmsg, error);
483
             logger.error(errmsg, error);
484
         }
484
         }

+ 20
- 19
modules/xmpp/recording.js Visa fil

2
 
2
 
3
 import { getLogger } from 'jitsi-meet-logger';
3
 import { getLogger } from 'jitsi-meet-logger';
4
 const logger = getLogger(__filename);
4
 const logger = getLogger(__filename);
5
-var XMPPEvents = require('../../service/xmpp/XMPPEvents');
6
-var JitsiRecorderErrors = require('../../JitsiRecorderErrors');
7
-var GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
5
+const XMPPEvents = require('../../service/xmpp/XMPPEvents');
6
+const JitsiRecorderErrors = require('../../JitsiRecorderErrors');
7
+const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
8
 
8
 
9
 
9
 
10
 function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
10
 function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
55
 };
55
 };
56
 
56
 
57
 Recording.prototype.handleJibriPresence = function(jibri) {
57
 Recording.prototype.handleJibriPresence = function(jibri) {
58
-    var attributes = jibri.attributes;
58
+    const attributes = jibri.attributes;
59
     if(!attributes) {
59
     if(!attributes) {
60
         return;
60
         return;
61
     }
61
     }
62
 
62
 
63
-    var newState = attributes.status;
63
+    const newState = attributes.status;
64
     logger.log('Handle jibri presence : ', newState);
64
     logger.log('Handle jibri presence : ', newState);
65
 
65
 
66
     if (newState === this.state) {
66
     if (newState === this.state) {
93
         options = options || {};
93
         options = options || {};
94
 
94
 
95
     // FIXME jibri does not accept IQ without 'url' attribute set ?
95
     // FIXME jibri does not accept IQ without 'url' attribute set ?
96
-        var iq = $iq({to: this.focusMucJid, type: 'set'})
96
+        const iq = $iq({to: this.focusMucJid, type: 'set'})
97
         .c('jibri', {
97
         .c('jibri', {
98
             'xmlns': 'http://jitsi.org/protocol/jibri',
98
             'xmlns': 'http://jitsi.org/protocol/jibri',
99
             'action': state === Recording.status.ON
99
             'action': state === Recording.status.ON
124
             errCallback(new Error('Invalid state!'));
124
             errCallback(new Error('Invalid state!'));
125
         }
125
         }
126
 
126
 
127
-        var iq = $iq({to: this.jirecon, type: 'set'})
127
+        const iq = $iq({to: this.jirecon, type: 'set'})
128
         .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
128
         .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
129
             action: state === Recording.status.ON
129
             action: state === Recording.status.ON
130
                 ? Recording.action.START
130
                 ? Recording.action.START
135
         }
135
         }
136
 
136
 
137
         logger.log('Start recording');
137
         logger.log('Start recording');
138
-        var self = this;
138
+        const self = this;
139
         this.connection.sendIQ(
139
         this.connection.sendIQ(
140
         iq,
140
         iq,
141
         function(result) {
141
         function(result) {
163
 // with the new recording state, according to the IQ.
163
 // with the new recording state, according to the IQ.
164
 Recording.prototype.setRecordingColibri
164
 Recording.prototype.setRecordingColibri
165
 = function(state, callback, errCallback, options) {
165
 = function(state, callback, errCallback, options) {
166
-    var elem = $iq({to: this.focusMucJid, type: 'set'});
166
+    const elem = $iq({to: this.focusMucJid, type: 'set'});
167
     elem.c('conference', {
167
     elem.c('conference', {
168
         xmlns: 'http://jitsi.org/protocol/colibri'
168
         xmlns: 'http://jitsi.org/protocol/colibri'
169
     });
169
     });
170
     elem.c('recording', {state, token: options.token});
170
     elem.c('recording', {state, token: options.token});
171
 
171
 
172
-    var self = this;
172
+    const self = this;
173
     this.connection.sendIQ(elem,
173
     this.connection.sendIQ(elem,
174
         function(result) {
174
         function(result) {
175
             logger.log('Set recording "', state, '". Result:', result);
175
             logger.log('Set recording "', state, '". Result:', result);
176
-            var recordingElem = $(result).find('>conference>recording');
177
-            var newState = recordingElem.attr('state');
176
+            const recordingElem = $(result).find('>conference>recording');
177
+            const newState = recordingElem.attr('state');
178
 
178
 
179
             self.state = newState;
179
             self.state = newState;
180
             callback(newState);
180
             callback(newState);
181
 
181
 
182
             if (newState === 'pending') {
182
             if (newState === 'pending') {
183
                 self.connection.addHandler(function(iq) {
183
                 self.connection.addHandler(function(iq) {
184
-                    var state = $(iq).find('recording').attr('state');
184
+                    const state = $(iq).find('recording').attr('state');
185
                     if (state) {
185
                     if (state) {
186
                         self.state = newState;
186
                         self.state = newState;
187
                         callback(state);
187
                         callback(state);
208
     case Recording.types.JIBRI:
208
     case Recording.types.JIBRI:
209
         this.setRecordingJibri(state, callback, errCallback, options);
209
         this.setRecordingJibri(state, callback, errCallback, options);
210
         break;
210
         break;
211
-    default:
212
-        var errmsg = 'Unknown recording type!';
211
+    default: {
212
+        const errmsg = 'Unknown recording type!';
213
         GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
213
         GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
214
         logger.error(errmsg);
214
         logger.error(errmsg);
215
-        return;
215
+        break;
216
+    }
216
     }
217
     }
217
 };
218
 };
218
 
219
 
222
  * @param statusChangeHandler {function} receives the new status as argument.
223
  * @param statusChangeHandler {function} receives the new status as argument.
223
  */
224
  */
224
 Recording.prototype.toggleRecording = function(options, statusChangeHandler) {
225
 Recording.prototype.toggleRecording = function(options, statusChangeHandler) {
225
-    var oldState = this.state;
226
+    const oldState = this.state;
226
 
227
 
227
     // If the recorder is currently unavailable we throw an error.
228
     // If the recorder is currently unavailable we throw an error.
228
     if (oldState === Recording.status.UNAVAILABLE
229
     if (oldState === Recording.status.UNAVAILABLE
247
         return;
248
         return;
248
     }
249
     }
249
 
250
 
250
-    var newState = oldState === Recording.status.AVAILABLE
251
+    const newState = oldState === Recording.status.AVAILABLE
251
                     || oldState === Recording.status.OFF
252
                     || oldState === Recording.status.OFF
252
                     ? Recording.status.ON
253
                     ? Recording.status.ON
253
                     : Recording.status.OFF;
254
                     : Recording.status.OFF;
254
 
255
 
255
-    var self = this;
256
+    const self = this;
256
     logger.log('Toggle recording (old state, new state): ', oldState, newState);
257
     logger.log('Toggle recording (old state, new state): ', oldState, newState);
257
     this.setRecording(newState,
258
     this.setRecording(newState,
258
         function(state, url) {
259
         function(state, url) {

+ 1
- 1
modules/xmpp/xmpp.js Visa fil

117
             logger.info('My Jabber ID: ' + this.connection.jid);
117
             logger.info('My Jabber ID: ' + this.connection.jid);
118
 
118
 
119
             // Schedule ping ?
119
             // Schedule ping ?
120
-            var pingJid = this.connection.domain;
120
+            const pingJid = this.connection.domain;
121
             this.connection.ping.hasPingSupport(
121
             this.connection.ping.hasPingSupport(
122
                 pingJid,
122
                 pingJid,
123
                 function(hasPing) {
123
                 function(hasPing) {

+ 1
- 1
service/RTC/CameraFacingMode.js Visa fil

7
  *
7
  *
8
  * @enum {string}
8
  * @enum {string}
9
  */
9
  */
10
-var CameraFacingMode = {
10
+const CameraFacingMode = {
11
     /**
11
     /**
12
      * The mode which specifies the environment-facing camera.
12
      * The mode which specifies the environment-facing camera.
13
      */
13
      */

+ 1
- 1
service/RTC/RTCEvents.js Visa fil

1
-var RTCEvents = {
1
+const RTCEvents = {
2
     /**
2
     /**
3
      * Indicates error while create answer call.
3
      * Indicates error while create answer call.
4
      */
4
      */

+ 1
- 1
service/RTC/Resolutions.js Visa fil

1
-var Resolutions = {
1
+const Resolutions = {
2
     '1080': {
2
     '1080': {
3
         width: 1920,
3
         width: 1920,
4
         height: 1080,
4
         height: 1080,

+ 1
- 1
service/RTC/StreamEventTypes.js Visa fil

1
-var StreamEventTypes = {
1
+const StreamEventTypes = {
2
     EVENT_TYPE_LOCAL_CREATED: 'stream.local_created',
2
     EVENT_TYPE_LOCAL_CREATED: 'stream.local_created',
3
 
3
 
4
     EVENT_TYPE_LOCAL_CHANGED: 'stream.local_changed',
4
     EVENT_TYPE_LOCAL_CHANGED: 'stream.local_changed',

+ 1
- 1
service/RTC/VideoType.js Visa fil

3
  * Enumeration of the video types
3
  * Enumeration of the video types
4
  * @type {{CAMERA: string, DESKTOP: string}}
4
  * @type {{CAMERA: string, DESKTOP: string}}
5
  */
5
  */
6
-var VideoType = {
6
+const VideoType = {
7
     /**
7
     /**
8
      * The camera video type.
8
      * The camera video type.
9
      */
9
      */

+ 1
- 1
service/authentication/AuthenticationEvents.js Visa fil

1
-var AuthenticationEvents = {
1
+const AuthenticationEvents = {
2
     /**
2
     /**
3
      * Event callback arguments:
3
      * Event callback arguments:
4
      * function(authenticationEnabled, userIdentity)
4
      * function(authenticationEnabled, userIdentity)

+ 1
- 1
service/statistics/constants.js Visa fil

1
-var Constants = {
1
+const Constants = {
2
     LOCAL_JID: 'local'
2
     LOCAL_JID: 'local'
3
 };
3
 };
4
 module.exports = Constants;
4
 module.exports = Constants;

+ 1
- 1
service/xmpp/XMPPEvents.js Visa fil

1
-var XMPPEvents = {
1
+const XMPPEvents = {
2
     /**
2
     /**
3
      * Indicates error while adding ice candidate.
3
      * Indicates error while adding ice candidate.
4
      */
4
      */

+ 5
- 5
webpack.config.js Visa fil

1
 /* global __dirname */
1
 /* global __dirname */
2
 
2
 
3
-var child_process = require('child_process'); // eslint-disable-line camelcase
4
-var process = require('process');
5
-var webpack = require('webpack');
3
+const child_process = require('child_process'); // eslint-disable-line camelcase
4
+const process = require('process');
5
+const webpack = require('webpack');
6
 
6
 
7
-var minimize
7
+const minimize
8
     = process.argv.indexOf('-p') !== -1
8
     = process.argv.indexOf('-p') !== -1
9
         || process.argv.indexOf('--optimize-minimize') !== -1;
9
         || process.argv.indexOf('--optimize-minimize') !== -1;
10
-var plugins = [];
10
+const plugins = [];
11
 
11
 
12
 if (minimize) {
12
 if (minimize) {
13
     // While webpack will automatically insert UglifyJsPlugin when minimize is
13
     // While webpack will automatically insert UglifyJsPlugin when minimize is

Laddar…
Avbryt
Spara