You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. //FIXME:
  4. import createRoomLocker from './modules/UI/authentication/RoomLocker';
  5. //FIXME:
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import ConnectionQuality from './modules/connectionquality/connectionquality';
  8. import Recorder from './modules/recorder/Recorder';
  9. import CQEvents from './service/connectionquality/CQEvents';
  10. import UIEvents from './service/UI/UIEvents';
  11. const ConnectionEvents = JitsiMeetJS.events.connection;
  12. const ConnectionErrors = JitsiMeetJS.errors.connection;
  13. const ConferenceEvents = JitsiMeetJS.events.conference;
  14. const ConferenceErrors = JitsiMeetJS.errors.conference;
  15. const TrackEvents = JitsiMeetJS.events.track;
  16. const TrackErrors = JitsiMeetJS.errors.track;
  17. let room, connection, localAudio, localVideo, roomLocker;
  18. let currentAudioInputDevices, currentVideoInputDevices;
  19. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  20. /**
  21. * Open Connection. When authentication failed it shows auth dialog.
  22. * @param roomName the room name to use
  23. * @returns Promise<JitsiConnection>
  24. */
  25. function connect(roomName) {
  26. return openConnection({retry: true, roomName: roomName})
  27. .catch(function (err) {
  28. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  29. APP.UI.notifyTokenAuthFailed();
  30. } else {
  31. APP.UI.notifyConnectionFailed(err);
  32. }
  33. throw err;
  34. });
  35. }
  36. /**
  37. * Share email with other users.
  38. * @param emailCommand the email command
  39. * @param {string} email new email
  40. */
  41. function sendEmail (emailCommand, email) {
  42. room.sendCommand(emailCommand, {
  43. value: email,
  44. attributes: {
  45. id: room.myUserId()
  46. }
  47. });
  48. }
  49. /**
  50. * Get user nickname by user id.
  51. * @param {string} id user id
  52. * @returns {string?} user nickname or undefined if user is unknown.
  53. */
  54. function getDisplayName (id) {
  55. if (APP.conference.isLocalId(id)) {
  56. return APP.settings.getDisplayName();
  57. }
  58. let participant = room.getParticipantById(id);
  59. if (participant && participant.getDisplayName()) {
  60. return participant.getDisplayName();
  61. }
  62. }
  63. /**
  64. * Mute or unmute local audio stream if it exists.
  65. * @param {boolean} muted if audio stream should be muted or unmuted.
  66. * @param {boolean} indicates if this local audio mute was a result of user
  67. * interaction
  68. *
  69. */
  70. function muteLocalAudio (muted, userInteraction) {
  71. if (!localAudio) {
  72. return;
  73. }
  74. if (muted) {
  75. localAudio.mute().then(function(value) {},
  76. function(value) {
  77. console.warn('Audio Mute was rejected:', value);
  78. }
  79. );
  80. } else {
  81. localAudio.unmute().then(function(value) {},
  82. function(value) {
  83. console.warn('Audio unmute was rejected:', value);
  84. }
  85. );
  86. }
  87. }
  88. /**
  89. * Mute or unmute local video stream if it exists.
  90. * @param {boolean} muted if video stream should be muted or unmuted.
  91. */
  92. function muteLocalVideo (muted) {
  93. if (!localVideo) {
  94. return;
  95. }
  96. if (muted) {
  97. localVideo.mute().then(function(value) {},
  98. function(value) {
  99. console.warn('Video mute was rejected:', value);
  100. }
  101. );
  102. } else {
  103. localVideo.unmute().then(function(value) {},
  104. function(value) {
  105. console.warn('Video unmute was rejected:', value);
  106. }
  107. );
  108. }
  109. }
  110. /**
  111. * Check if the welcome page is enabled and redirects to it.
  112. */
  113. function maybeRedirectToWelcomePage() {
  114. if (!config.enableWelcomePage) {
  115. return;
  116. }
  117. // redirect to welcome page
  118. setTimeout(() => {
  119. APP.settings.setWelcomePageEnabled(true);
  120. window.location.pathname = "/";
  121. }, 3000);
  122. }
  123. /**
  124. * Executes connection.disconnect and shows the feedback dialog
  125. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  126. * @returns Promise.
  127. */
  128. function disconnectAndShowFeedback(requestFeedback) {
  129. connection.disconnect();
  130. if (requestFeedback) {
  131. return APP.UI.requestFeedback();
  132. } else {
  133. return Promise.resolve();
  134. }
  135. }
  136. /**
  137. * Disconnect from the conference and optionally request user feedback.
  138. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  139. */
  140. function hangup (requestFeedback = false) {
  141. const errCallback = (f, err) => {
  142. console.error('Error occurred during hanging up: ', err);
  143. return f();
  144. };
  145. const disconnect = disconnectAndShowFeedback.bind(null, requestFeedback);
  146. APP.conference._room.leave()
  147. .then(disconnect)
  148. .catch(errCallback.bind(null, disconnect))
  149. .then(maybeRedirectToWelcomePage)
  150. .catch(errCallback.bind(null, maybeRedirectToWelcomePage));
  151. }
  152. /**
  153. * Create local tracks of specified types.
  154. * @param {string[]} devices - required track types ('audio', 'video' etc.)
  155. * @param {string|null} [cameraDeviceId] - camera device id, if undefined - one
  156. * from settings will be used
  157. * @param {string|null} [micDeviceId] - microphone device id, if undefined - one
  158. * from settings will be used
  159. * @returns {Promise<JitsiLocalTrack[]>}
  160. */
  161. function createLocalTracks (devices, cameraDeviceId, micDeviceId) {
  162. return JitsiMeetJS.createLocalTracks({
  163. // copy array to avoid mutations inside library
  164. devices: devices.slice(0),
  165. resolution: config.resolution,
  166. cameraDeviceId: typeof cameraDeviceId === 'undefined'
  167. || cameraDeviceId === null
  168. ? APP.settings.getCameraDeviceId()
  169. : cameraDeviceId,
  170. micDeviceId: typeof micDeviceId === 'undefined' || micDeviceId === null
  171. ? APP.settings.getMicDeviceId()
  172. : micDeviceId,
  173. // adds any ff fake device settings if any
  174. firefox_fake_device: config.firefox_fake_device
  175. }).catch(function (err) {
  176. console.error('failed to create local tracks', ...devices, err);
  177. return Promise.reject(err);
  178. });
  179. }
  180. /**
  181. * Stores lists of current 'audioinput' and 'videoinput' devices
  182. * @param {MediaDeviceInfo[]} devices
  183. */
  184. function setCurrentMediaDevices(devices) {
  185. currentAudioInputDevices = devices.filter(
  186. d => d.kind === 'audioinput');
  187. currentVideoInputDevices = devices.filter(
  188. d => d.kind === 'videoinput');
  189. }
  190. class ConferenceConnector {
  191. constructor(resolve, reject) {
  192. this._resolve = resolve;
  193. this._reject = reject;
  194. this.reconnectTimeout = null;
  195. room.on(ConferenceEvents.CONFERENCE_JOINED,
  196. this._handleConferenceJoined.bind(this));
  197. room.on(ConferenceEvents.CONFERENCE_FAILED,
  198. this._onConferenceFailed.bind(this));
  199. room.on(ConferenceEvents.CONFERENCE_ERROR,
  200. this._onConferenceError.bind(this));
  201. }
  202. _handleConferenceFailed(err, msg) {
  203. this._unsubscribe();
  204. this._reject(err);
  205. }
  206. _onConferenceFailed(err, ...params) {
  207. console.error('CONFERENCE FAILED:', err, ...params);
  208. switch (err) {
  209. // room is locked by the password
  210. case ConferenceErrors.PASSWORD_REQUIRED:
  211. APP.UI.markRoomLocked(true);
  212. roomLocker.requirePassword().then(function () {
  213. room.join(roomLocker.password);
  214. });
  215. break;
  216. case ConferenceErrors.CONNECTION_ERROR:
  217. {
  218. let [msg] = params;
  219. APP.UI.notifyConnectionFailed(msg);
  220. }
  221. break;
  222. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  223. APP.UI.notifyBridgeDown();
  224. break;
  225. // not enough rights to create conference
  226. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  227. // schedule reconnect to check if someone else created the room
  228. this.reconnectTimeout = setTimeout(function () {
  229. room.join();
  230. }, 5000);
  231. // notify user that auth is required
  232. AuthHandler.requireAuth(room, roomLocker.password);
  233. break;
  234. case ConferenceErrors.RESERVATION_ERROR:
  235. {
  236. let [code, msg] = params;
  237. APP.UI.notifyReservationError(code, msg);
  238. }
  239. break;
  240. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  241. APP.UI.notifyGracefulShutdown();
  242. break;
  243. case ConferenceErrors.JINGLE_FATAL_ERROR:
  244. APP.UI.notifyInternalError();
  245. break;
  246. case ConferenceErrors.CONFERENCE_DESTROYED:
  247. {
  248. let [reason] = params;
  249. APP.UI.hideStats();
  250. APP.UI.notifyConferenceDestroyed(reason);
  251. }
  252. break;
  253. case ConferenceErrors.FOCUS_DISCONNECTED:
  254. {
  255. let [focus, retrySec] = params;
  256. APP.UI.notifyFocusDisconnected(focus, retrySec);
  257. }
  258. break;
  259. case ConferenceErrors.FOCUS_LEFT:
  260. room.leave().then(() => connection.disconnect());
  261. APP.UI.notifyFocusLeft();
  262. break;
  263. case ConferenceErrors.CONFERENCE_MAX_USERS:
  264. connection.disconnect();
  265. APP.UI.notifyMaxUsersLimitReached();
  266. break;
  267. default:
  268. this._handleConferenceFailed(err, ...params);
  269. }
  270. }
  271. _onConferenceError(err, ...params) {
  272. console.error('CONFERENCE Error:', err, params);
  273. switch (err) {
  274. case ConferenceErrors.CHAT_ERROR:
  275. {
  276. let [code, msg] = params;
  277. APP.UI.showChatError(code, msg);
  278. }
  279. break;
  280. default:
  281. console.error("Unknown error.");
  282. }
  283. }
  284. _unsubscribe() {
  285. room.off(
  286. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  287. room.off(
  288. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  289. if (this.reconnectTimeout !== null) {
  290. clearTimeout(this.reconnectTimeout);
  291. }
  292. AuthHandler.closeAuth();
  293. }
  294. _handleConferenceJoined() {
  295. this._unsubscribe();
  296. this._resolve();
  297. }
  298. connect() {
  299. room.join();
  300. }
  301. }
  302. export default {
  303. localId: undefined,
  304. isModerator: false,
  305. audioMuted: false,
  306. videoMuted: false,
  307. isSharingScreen: false,
  308. isDesktopSharingEnabled: false,
  309. /**
  310. * Open new connection and join to the conference.
  311. * @param {object} options
  312. * @param {string} roomName name of the conference
  313. * @returns {Promise}
  314. */
  315. init(options) {
  316. let self = this;
  317. this.roomName = options.roomName;
  318. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  319. // attaches global error handler, if there is already one, respect it
  320. if(JitsiMeetJS.getGlobalOnErrorHandler){
  321. var oldOnErrorHandler = window.onerror;
  322. window.onerror = function (message, source, lineno, colno, error) {
  323. JitsiMeetJS.getGlobalOnErrorHandler(
  324. message, source, lineno, colno, error);
  325. if(oldOnErrorHandler)
  326. oldOnErrorHandler(message, source, lineno, colno, error);
  327. };
  328. var oldOnUnhandledRejection = window.onunhandledrejection;
  329. window.onunhandledrejection = function(event) {
  330. JitsiMeetJS.getGlobalOnErrorHandler(
  331. null, null, null, null, event.reason);
  332. if(oldOnUnhandledRejection)
  333. oldOnUnhandledRejection(event);
  334. };
  335. }
  336. let audioAndVideoError, audioOnlyError;
  337. return JitsiMeetJS.init(config).then(() => {
  338. return Promise.all([
  339. // try to retrieve audio and video
  340. createLocalTracks(['audio', 'video'])
  341. // if failed then try to retrieve only audio
  342. .catch(err => {
  343. audioAndVideoError = err;
  344. return createLocalTracks(['audio']);
  345. })
  346. // if audio also failed then just return empty array
  347. .catch(err => {
  348. audioOnlyError = err;
  349. return [];
  350. }),
  351. connect(options.roomName)
  352. ]);
  353. }).then(([tracks, con]) => {
  354. if (audioAndVideoError) {
  355. if (audioOnlyError) {
  356. // If both requests for 'audio' + 'video' and 'audio' only
  357. // failed, we assume that there is some problems with user's
  358. // microphone and show corresponding dialog.
  359. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  360. } else {
  361. // If request for 'audio' + 'video' failed, but request for
  362. // 'audio' only was OK, we assume that we had problems with
  363. // camera and show corresponding dialog.
  364. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  365. }
  366. }
  367. console.log('initialized with %s local tracks', tracks.length);
  368. APP.connection = connection = con;
  369. this._createRoom(tracks);
  370. this.isDesktopSharingEnabled =
  371. JitsiMeetJS.isDesktopSharingEnabled();
  372. // if user didn't give access to mic or camera or doesn't have
  373. // them at all, we disable corresponding toolbar buttons
  374. if (!tracks.find((t) => t.isAudioTrack())) {
  375. APP.UI.disableMicrophoneButton();
  376. }
  377. if (!tracks.find((t) => t.isVideoTrack())) {
  378. APP.UI.disableCameraButton();
  379. }
  380. // update list of available devices
  381. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  382. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  383. JitsiMeetJS.mediaDevices.enumerateDevices(function(devices) {
  384. // Ugly way to synchronize real device IDs with local
  385. // storage and settings menu. This is a workaround until
  386. // getConstraints() method will be implemented in browsers.
  387. if (localAudio) {
  388. localAudio._setRealDeviceIdFromDeviceList(devices);
  389. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  390. }
  391. if (localVideo) {
  392. localVideo._setRealDeviceIdFromDeviceList(devices);
  393. APP.settings.setCameraDeviceId(
  394. localVideo.getDeviceId());
  395. }
  396. setCurrentMediaDevices(devices);
  397. APP.UI.onAvailableDevicesChanged(devices);
  398. });
  399. JitsiMeetJS.mediaDevices.addEventListener(
  400. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  401. (devices) => {
  402. // Just defer callback until other event callbacks are
  403. // processed.
  404. window.setTimeout(() => {
  405. checkLocalDevicesAfterDeviceListChanged(devices)
  406. .then(() => {
  407. setCurrentMediaDevices(devices);
  408. APP.UI.onAvailableDevicesChanged(devices);
  409. });
  410. }, 0);
  411. });
  412. }
  413. if (config.iAmRecorder)
  414. this.recorder = new Recorder();
  415. // XXX The API will take care of disconnecting from the XMPP server
  416. // (and, thus, leaving the room) on unload.
  417. return new Promise((resolve, reject) => {
  418. (new ConferenceConnector(resolve, reject)).connect();
  419. });
  420. function checkAudioOutputDeviceAfterDeviceListChanged(newDevices) {
  421. if (!JitsiMeetJS.mediaDevices
  422. .isDeviceChangeAvailable('output')) {
  423. return;
  424. }
  425. var selectedAudioOutputDeviceId =
  426. APP.settings.getAudioOutputDeviceId(),
  427. availableAudioOutputDevices = newDevices.filter(d => {
  428. return d.kind === 'audiooutput';
  429. });
  430. if (selectedAudioOutputDeviceId !== 'default' &&
  431. !availableAudioOutputDevices.find(d =>
  432. d.deviceId === selectedAudioOutputDeviceId)) {
  433. APP.settings.setAudioOutputDeviceId('default');
  434. }
  435. }
  436. function checkLocalDevicesAfterDeviceListChanged(newDevices) {
  437. // Event handler can be fire before direct enumerateDevices()
  438. // call, so handle this situation here.
  439. if (!currentAudioInputDevices && !currentVideoInputDevices) {
  440. setCurrentMediaDevices(newDevices);
  441. }
  442. checkAudioOutputDeviceAfterDeviceListChanged(newDevices);
  443. let availableAudioInputDevices = newDevices.filter(
  444. d => d.kind === 'audioinput'),
  445. availableVideoInputDevices = newDevices.filter(
  446. d => d.kind === 'videoinput'),
  447. selectedAudioInputDeviceId = APP.settings.getMicDeviceId(),
  448. selectedVideoInputDeviceId =
  449. APP.settings.getCameraDeviceId(),
  450. selectedAudioInputDevice = availableAudioInputDevices.find(
  451. d => d.deviceId === selectedAudioInputDeviceId),
  452. selectedVideoInputDevice = availableVideoInputDevices.find(
  453. d => d.deviceId === selectedVideoInputDeviceId),
  454. tracksToCreate = [],
  455. micIdToUse = null,
  456. cameraIdToUse = null;
  457. // Here we handle case when no device was initially plugged, but
  458. // then it's connected OR new device was connected when previous
  459. // track has ended.
  460. if (!localAudio || localAudio.disposed || localAudio.isEnded()){
  461. if (availableAudioInputDevices.length
  462. && availableAudioInputDevices[0].label !== '') {
  463. tracksToCreate.push('audio');
  464. micIdToUse = availableAudioInputDevices[0].deviceId;
  465. } else {
  466. APP.UI.disableMicrophoneButton();
  467. }
  468. }
  469. if ((!localVideo || localVideo.disposed || localVideo.isEnded())
  470. && !self.isSharingScreen){
  471. if (availableVideoInputDevices.length
  472. && availableVideoInputDevices[0].label !== '') {
  473. tracksToCreate.push('video');
  474. cameraIdToUse = availableVideoInputDevices[0].deviceId;
  475. } else {
  476. APP.UI.disableCameraButton();
  477. }
  478. }
  479. if (localAudio && !localAudio.disposed && !localAudio.isEnded()
  480. && selectedAudioInputDevice
  481. && selectedAudioInputDeviceId !== localAudio.getDeviceId()
  482. && tracksToCreate.indexOf('audio') === -1) {
  483. tracksToCreate.push('audio');
  484. micIdToUse = selectedAudioInputDeviceId;
  485. }
  486. if (localVideo && !localVideo.disposed && !localVideo.isEnded()
  487. && selectedVideoInputDevice
  488. && selectedVideoInputDeviceId !== localVideo.getDeviceId()
  489. && tracksToCreate.indexOf('video') === -1
  490. && !self.isSharingScreen) {
  491. tracksToCreate.push('video');
  492. cameraIdToUse = selectedVideoInputDeviceId;
  493. }
  494. if (tracksToCreate.length) {
  495. return createNewTracks(
  496. tracksToCreate, cameraIdToUse, micIdToUse);
  497. } else {
  498. return Promise.resolve();
  499. }
  500. function createNewTracks(type, cameraDeviceId, micDeviceId) {
  501. let audioTrackCreationError;
  502. let videoTrackCreationError;
  503. let audioRequested = type.indexOf('audio') !== -1;
  504. let videoRequested = type.indexOf('video') !== -1;
  505. let promise;
  506. if (audioRequested && micDeviceId !== null) {
  507. if (videoRequested && cameraDeviceId !== null) {
  508. promise = createLocalTracks(
  509. type, cameraDeviceId, micDeviceId)
  510. .catch(() => {
  511. return Promise.all([
  512. createAudioTrack(false),
  513. createVideoTrack(false)]);
  514. })
  515. .then((audioTracks, videoTracks) => {
  516. if (audioTrackCreationError) {
  517. if (videoTrackCreationError) {
  518. APP.UI.showDeviceErrorDialog(
  519. audioTrackCreationError,
  520. videoTrackCreationError);
  521. } else {
  522. APP.UI.showDeviceErrorDialog(
  523. audioTrackCreationError,
  524. null);
  525. }
  526. } else if (videoTrackCreationError) {
  527. APP.UI.showDeviceErrorDialog(
  528. null,
  529. videoTrackCreationError);
  530. }
  531. return audioTracks.concat(videoTracks);
  532. });
  533. } else {
  534. promise = createAudioTrack();
  535. }
  536. } else if (videoRequested && cameraDeviceId !== null) {
  537. promise = createVideoTrack();
  538. } else {
  539. promise = Promise.resolve([]);
  540. }
  541. return promise
  542. .then(onTracksCreated);
  543. function createAudioTrack(showError) {
  544. return createLocalTracks(['audio'], null, micDeviceId)
  545. .catch(err => {
  546. audioTrackCreationError = err;
  547. if (showError) {
  548. APP.UI.showDeviceErrorDialog(err, null);
  549. }
  550. return [];
  551. });
  552. }
  553. function createVideoTrack(showError) {
  554. return createLocalTracks(
  555. ['video'], cameraDeviceId, null)
  556. .catch(err => {
  557. videoTrackCreationError = err;
  558. if (showError) {
  559. APP.UI.showDeviceErrorDialog(null, err);
  560. }
  561. return [];
  562. });
  563. }
  564. }
  565. function onTracksCreated(tracks) {
  566. return Promise.all((tracks || []).map(track => {
  567. if (track.isAudioTrack()) {
  568. let audioWasMuted = self.audioMuted;
  569. return self.useAudioStream(track).then(() => {
  570. console.log('switched local audio');
  571. // If we plugged-in new device (and switched to
  572. // it), but video was muted before, or we
  573. // unplugged current device and selected new
  574. // one, then mute new video track.
  575. if (audioWasMuted ||
  576. currentAudioInputDevices.length >
  577. availableAudioInputDevices.length) {
  578. muteLocalAudio(true);
  579. }
  580. });
  581. } else if (track.isVideoTrack()) {
  582. let videoWasMuted = self.videoMuted;
  583. return self.useVideoStream(track).then(() => {
  584. console.log('switched local video');
  585. // TODO: maybe make video large if we
  586. // are not in conference yet
  587. // If we plugged-in new device (and switched to
  588. // it), but video was muted before, or we
  589. // unplugged current device and selected new
  590. // one, then mute new video track.
  591. if (videoWasMuted ||
  592. (currentVideoInputDevices.length >
  593. availableVideoInputDevices.length)) {
  594. muteLocalVideo(true);
  595. }
  596. });
  597. } else {
  598. console.error("Ignored not an audio nor a "
  599. + "video track: ", track);
  600. return Promise.resolve();
  601. }
  602. }));
  603. }
  604. }
  605. });
  606. },
  607. /**
  608. * Check if id is id of the local user.
  609. * @param {string} id id to check
  610. * @returns {boolean}
  611. */
  612. isLocalId (id) {
  613. return this.localId === id;
  614. },
  615. /**
  616. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  617. * @param mute true for mute and false for unmute.
  618. */
  619. muteAudio (mute) {
  620. muteLocalAudio(mute);
  621. },
  622. /**
  623. * Returns whether local audio is muted or not.
  624. * @returns {boolean}
  625. */
  626. isLocalAudioMuted() {
  627. return this.audioMuted;
  628. },
  629. /**
  630. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  631. */
  632. toggleAudioMuted () {
  633. this.muteAudio(!this.audioMuted);
  634. },
  635. /**
  636. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  637. * @param mute true for mute and false for unmute.
  638. */
  639. muteVideo (mute) {
  640. muteLocalVideo(mute);
  641. },
  642. /**
  643. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  644. */
  645. toggleVideoMuted () {
  646. this.muteVideo(!this.videoMuted);
  647. },
  648. /**
  649. * Retrieve list of conference participants (without local user).
  650. * @returns {JitsiParticipant[]}
  651. */
  652. listMembers () {
  653. return room.getParticipants();
  654. },
  655. /**
  656. * Retrieve list of ids of conference participants (without local user).
  657. * @returns {string[]}
  658. */
  659. listMembersIds () {
  660. return room.getParticipants().map(p => p.getId());
  661. },
  662. /**
  663. * Checks whether the participant identified by id is a moderator.
  664. * @id id to search for participant
  665. * @return {boolean} whether the participant is moderator
  666. */
  667. isParticipantModerator (id) {
  668. let user = room.getParticipantById(id);
  669. return user && user.isModerator();
  670. },
  671. /**
  672. * Check if SIP is supported.
  673. * @returns {boolean}
  674. */
  675. sipGatewayEnabled () {
  676. return room.isSIPCallingSupported();
  677. },
  678. get membersCount () {
  679. return room.getParticipants().length + 1;
  680. },
  681. /**
  682. * Returns true if the callstats integration is enabled, otherwise returns
  683. * false.
  684. *
  685. * @returns true if the callstats integration is enabled, otherwise returns
  686. * false.
  687. */
  688. isCallstatsEnabled () {
  689. return room.isCallstatsEnabled();
  690. },
  691. /**
  692. * Sends the given feedback through CallStats if enabled.
  693. *
  694. * @param overallFeedback an integer between 1 and 5 indicating the
  695. * user feedback
  696. * @param detailedFeedback detailed feedback from the user. Not yet used
  697. */
  698. sendFeedback (overallFeedback, detailedFeedback) {
  699. return room.sendFeedback (overallFeedback, detailedFeedback);
  700. },
  701. // used by torture currently
  702. isJoined () {
  703. return this._room
  704. && this._room.isJoined();
  705. },
  706. getConnectionState () {
  707. return this._room
  708. && this._room.getConnectionState();
  709. },
  710. getMyUserId () {
  711. return this._room
  712. && this._room.myUserId();
  713. },
  714. /**
  715. * Indicates if recording is supported in this conference.
  716. */
  717. isRecordingSupported() {
  718. return this._room && this._room.isRecordingSupported();
  719. },
  720. /**
  721. * Returns the recording state or undefined if the room is not defined.
  722. */
  723. getRecordingState() {
  724. return (this._room) ? this._room.getRecordingState() : undefined;
  725. },
  726. /**
  727. * Will be filled with values only when config.debug is enabled.
  728. * Its used by torture to check audio levels.
  729. */
  730. audioLevelsMap: {},
  731. /**
  732. * Returns the stored audio level (stored only if config.debug is enabled)
  733. * @param id the id for the user audio level to return (the id value is
  734. * returned for the participant using getMyUserId() method)
  735. */
  736. getPeerSSRCAudioLevel (id) {
  737. return this.audioLevelsMap[id];
  738. },
  739. /**
  740. * @return {number} the number of participants in the conference with at
  741. * least one track.
  742. */
  743. getNumberOfParticipantsWithTracks() {
  744. return this._room.getParticipants()
  745. .filter((p) => p.getTracks().length > 0)
  746. .length;
  747. },
  748. /**
  749. * Returns the stats.
  750. */
  751. getStats() {
  752. return ConnectionQuality.getStats();
  753. },
  754. // end used by torture
  755. getLogs () {
  756. return room.getLogs();
  757. },
  758. /**
  759. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  760. * desire to keep room private to this instance and (2) the need of other
  761. * modules to send and receive commands to and from participants.
  762. * Eventually, this instance remains in control with respect to the
  763. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  764. * JitsiConference) is to be used in the implementation of the Command(s)
  765. * API of this instance.
  766. */
  767. commands: {
  768. /**
  769. * Known custom conference commands.
  770. */
  771. defaults: {
  772. CONNECTION_QUALITY: "stats",
  773. EMAIL: "email",
  774. ETHERPAD: "etherpad",
  775. SHARED_VIDEO: "shared-video",
  776. CUSTOM_ROLE: "custom-role"
  777. },
  778. /**
  779. * Receives notifications from other participants about commands aka
  780. * custom events (sent by sendCommand or sendCommandOnce methods).
  781. * @param command {String} the name of the command
  782. * @param handler {Function} handler for the command
  783. */
  784. addCommandListener () {
  785. room.addCommandListener.apply(room, arguments);
  786. },
  787. /**
  788. * Removes command.
  789. * @param name {String} the name of the command.
  790. */
  791. removeCommand () {
  792. room.removeCommand.apply(room, arguments);
  793. },
  794. /**
  795. * Sends command.
  796. * @param name {String} the name of the command.
  797. * @param values {Object} with keys and values that will be sent.
  798. */
  799. sendCommand () {
  800. room.sendCommand.apply(room, arguments);
  801. },
  802. /**
  803. * Sends command one time.
  804. * @param name {String} the name of the command.
  805. * @param values {Object} with keys and values that will be sent.
  806. */
  807. sendCommandOnce () {
  808. room.sendCommandOnce.apply(room, arguments);
  809. }
  810. },
  811. _createRoom (localTracks) {
  812. room = connection.initJitsiConference(APP.conference.roomName,
  813. this._getConferenceOptions());
  814. this.localId = room.myUserId();
  815. localTracks.forEach((track) => {
  816. if (track.isAudioTrack()) {
  817. this.useAudioStream(track);
  818. } else if (track.isVideoTrack()) {
  819. this.useVideoStream(track);
  820. } else {
  821. console.error(
  822. "Ignored not an audio nor a video track: ", track);
  823. }
  824. });
  825. roomLocker = createRoomLocker(room);
  826. this._room = room; // FIXME do not use this
  827. let email = APP.settings.getEmail();
  828. email && sendEmail(this.commands.defaults.EMAIL, email);
  829. let nick = APP.settings.getDisplayName();
  830. if (config.useNicks && !nick) {
  831. nick = APP.UI.askForNickname();
  832. APP.settings.setDisplayName(nick);
  833. }
  834. nick && room.setDisplayName(nick);
  835. this._setupListeners();
  836. },
  837. _getConferenceOptions() {
  838. let options = config;
  839. if(config.enableRecording && !config.recordingType) {
  840. options.recordingType = (config.hosts &&
  841. (typeof config.hosts.jirecon != "undefined"))?
  842. "jirecon" : "colibri";
  843. }
  844. return options;
  845. },
  846. /**
  847. * Start using provided video stream.
  848. * Stops previous video stream.
  849. * @param {JitsiLocalTrack} [stream] new stream to use or null
  850. * @returns {Promise}
  851. */
  852. useVideoStream (stream) {
  853. let promise = Promise.resolve();
  854. if (localVideo) {
  855. // this calls room.removeTrack internally
  856. // so we don't need to remove it manually
  857. promise = localVideo.dispose();
  858. }
  859. localVideo = stream;
  860. return promise.then(function () {
  861. if (stream) {
  862. return room.addTrack(stream);
  863. }
  864. }).then(() => {
  865. if (stream) {
  866. this.videoMuted = stream.isMuted();
  867. this.isSharingScreen = stream.videoType === 'desktop';
  868. APP.UI.addLocalStream(stream);
  869. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  870. } else {
  871. this.videoMuted = false;
  872. this.isSharingScreen = false;
  873. }
  874. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  875. APP.UI.updateDesktopSharingButtons();
  876. });
  877. },
  878. /**
  879. * Start using provided audio stream.
  880. * Stops previous audio stream.
  881. * @param {JitsiLocalTrack} [stream] new stream to use or null
  882. * @returns {Promise}
  883. */
  884. useAudioStream (stream) {
  885. let promise = Promise.resolve();
  886. if (localAudio) {
  887. // this calls room.removeTrack internally
  888. // so we don't need to remove it manually
  889. promise = localAudio.dispose();
  890. }
  891. localAudio = stream;
  892. return promise.then(function () {
  893. if (stream) {
  894. return room.addTrack(stream);
  895. }
  896. }).then(() => {
  897. if (stream) {
  898. this.audioMuted = stream.isMuted();
  899. APP.UI.addLocalStream(stream);
  900. } else {
  901. this.audioMuted = false;
  902. }
  903. APP.UI.enableMicrophoneButton();
  904. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  905. });
  906. },
  907. videoSwitchInProgress: false,
  908. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  909. if (this.videoSwitchInProgress) {
  910. console.warn("Switch in progress.");
  911. return;
  912. }
  913. if (!this.isDesktopSharingEnabled) {
  914. console.warn("Cannot toggle screen sharing: not supported.");
  915. return;
  916. }
  917. this.videoSwitchInProgress = true;
  918. if (shareScreen) {
  919. createLocalTracks(['desktop']).then(([stream]) => {
  920. stream.on(
  921. TrackEvents.LOCAL_TRACK_STOPPED,
  922. () => {
  923. // if stream was stopped during screensharing session
  924. // then we should switch to video
  925. // otherwise we stopped it because we already switched
  926. // to video, so nothing to do here
  927. if (this.isSharingScreen) {
  928. this.toggleScreenSharing(false);
  929. }
  930. }
  931. );
  932. return this.useVideoStream(stream);
  933. }).then(() => {
  934. this.videoSwitchInProgress = false;
  935. console.log('sharing local desktop');
  936. }).catch((err) => {
  937. this.videoSwitchInProgress = false;
  938. this.toggleScreenSharing(false);
  939. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  940. return;
  941. }
  942. console.error('failed to share local desktop', err);
  943. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  944. APP.UI.showExtensionRequiredDialog(
  945. config.desktopSharingFirefoxExtensionURL
  946. );
  947. return;
  948. }
  949. // Handling:
  950. // TrackErrors.PERMISSION_DENIED
  951. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  952. // TrackErrors.GENERAL
  953. // and any other
  954. let dialogTxt;
  955. let dialogTitle;
  956. if (err.name === TrackErrors.PERMISSION_DENIED) {
  957. dialogTxt = APP.translation.generateTranslationHTML(
  958. "dialog.screenSharingPermissionDeniedError");
  959. dialogTitle = APP.translation.generateTranslationHTML(
  960. "dialog.error");
  961. } else {
  962. dialogTxt = APP.translation.generateTranslationHTML(
  963. "dialog.failtoinstall");
  964. dialogTitle = APP.translation.generateTranslationHTML(
  965. "dialog.permissionDenied");
  966. }
  967. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  968. });
  969. } else {
  970. createLocalTracks(['video']).then(
  971. ([stream]) => this.useVideoStream(stream)
  972. ).then(() => {
  973. this.videoSwitchInProgress = false;
  974. console.log('sharing local video');
  975. }).catch((err) => {
  976. this.useVideoStream(null);
  977. this.videoSwitchInProgress = false;
  978. console.error('failed to share local video', err);
  979. });
  980. }
  981. },
  982. /**
  983. * Setup interaction between conference and UI.
  984. */
  985. _setupListeners () {
  986. // add local streams when joined to the conference
  987. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  988. APP.UI.mucJoined();
  989. });
  990. room.on(
  991. ConferenceEvents.AUTH_STATUS_CHANGED,
  992. function (authEnabled, authLogin) {
  993. APP.UI.updateAuthInfo(authEnabled, authLogin);
  994. }
  995. );
  996. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  997. if (user.isHidden())
  998. return;
  999. console.log('USER %s connnected', id, user);
  1000. APP.API.notifyUserJoined(id);
  1001. APP.UI.addUser(id, user.getDisplayName());
  1002. // check the roles for the new user and reflect them
  1003. APP.UI.updateUserRole(user);
  1004. });
  1005. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1006. console.log('USER %s LEFT', id, user);
  1007. APP.API.notifyUserLeft(id);
  1008. APP.UI.removeUser(id, user.getDisplayName());
  1009. APP.UI.onSharedVideoStop(id);
  1010. });
  1011. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1012. if (this.isLocalId(id)) {
  1013. console.info(`My role changed, new role: ${role}`);
  1014. this.isModerator = room.isModerator();
  1015. APP.UI.updateLocalRole(room.isModerator());
  1016. } else {
  1017. let user = room.getParticipantById(id);
  1018. if (user) {
  1019. APP.UI.updateUserRole(user);
  1020. }
  1021. }
  1022. });
  1023. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1024. if(!track || track.isLocal())
  1025. return;
  1026. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1027. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1028. });
  1029. APP.UI.addRemoteStream(track);
  1030. });
  1031. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1032. if(!track || track.isLocal())
  1033. return;
  1034. APP.UI.removeRemoteStream(track);
  1035. });
  1036. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1037. if(!track)
  1038. return;
  1039. const handler = (track.getType() === "audio")?
  1040. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1041. let id;
  1042. const mute = track.isMuted();
  1043. if(track.isLocal()){
  1044. id = this.localId;
  1045. if(track.getType() === "audio") {
  1046. this.audioMuted = mute;
  1047. } else {
  1048. this.videoMuted = mute;
  1049. }
  1050. } else {
  1051. id = track.getParticipantId();
  1052. }
  1053. handler(id , mute);
  1054. });
  1055. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1056. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1057. lvl = 0;
  1058. }
  1059. if(config.debug)
  1060. {
  1061. this.audioLevelsMap[id] = lvl;
  1062. if(config.debugAudioLevels)
  1063. console.log("AudioLevel:" + id + "/" + lvl);
  1064. }
  1065. APP.UI.setAudioLevel(id, lvl);
  1066. });
  1067. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1068. //FIXME
  1069. if (config.muteLocalVideoIfNotInLastN) {
  1070. // TODO mute or unmute if required
  1071. // mark video on UI
  1072. // APP.UI.markVideoMuted(true/false);
  1073. }
  1074. });
  1075. room.on(
  1076. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1077. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1078. });
  1079. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1080. APP.UI.markDominantSpeaker(id);
  1081. });
  1082. if (!interfaceConfig.filmStripOnly) {
  1083. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1084. APP.UI.markVideoInterrupted(true);
  1085. });
  1086. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1087. APP.UI.markVideoInterrupted(false);
  1088. });
  1089. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1090. let nick = getDisplayName(id);
  1091. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1092. APP.UI.addMessage(id, nick, text, ts);
  1093. });
  1094. }
  1095. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1096. APP.API.notifyDisplayNameChanged(id, displayName);
  1097. APP.UI.changeDisplayName(id, displayName);
  1098. });
  1099. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1100. console.log("Received recorder status change: ", status, error);
  1101. APP.UI.updateRecordingState(status);
  1102. });
  1103. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1104. APP.UI.updateUserStatus(id, status);
  1105. });
  1106. room.on(ConferenceEvents.KICKED, () => {
  1107. APP.UI.hideStats();
  1108. APP.UI.notifyKicked();
  1109. // FIXME close
  1110. });
  1111. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1112. APP.UI.updateDTMFSupport(isDTMFSupported);
  1113. });
  1114. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1115. if (room.isModerator()) {
  1116. let promise = roomLocker.isLocked
  1117. ? roomLocker.askToUnlock()
  1118. : roomLocker.askToLock();
  1119. promise.then(() => {
  1120. APP.UI.markRoomLocked(roomLocker.isLocked);
  1121. });
  1122. } else {
  1123. roomLocker.notifyModeratorRequired();
  1124. }
  1125. });
  1126. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1127. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1128. if (!interfaceConfig.filmStripOnly) {
  1129. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1130. APP.API.notifySendingChatMessage(message);
  1131. room.sendTextMessage(message);
  1132. });
  1133. }
  1134. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1135. ConnectionQuality.updateLocalStats(stats);
  1136. });
  1137. ConnectionQuality.addListener(
  1138. CQEvents.LOCALSTATS_UPDATED,
  1139. (percent, stats) => {
  1140. APP.UI.updateLocalStats(percent, stats);
  1141. // send local stats to other users
  1142. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  1143. {
  1144. children: ConnectionQuality.convertToMUCStats(stats),
  1145. attributes: {
  1146. xmlns: 'http://jitsi.org/jitmeet/stats'
  1147. }
  1148. });
  1149. }
  1150. );
  1151. // listen to remote stats
  1152. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  1153. (values, from) => {
  1154. ConnectionQuality.updateRemoteStats(from, values);
  1155. });
  1156. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1157. (id, percent, stats) => {
  1158. APP.UI.updateRemoteStats(id, percent, stats);
  1159. });
  1160. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1161. APP.UI.initEtherpad(value);
  1162. });
  1163. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  1164. email = email.trim();
  1165. if (email === APP.settings.getEmail()) {
  1166. return;
  1167. }
  1168. APP.settings.setEmail(email);
  1169. APP.UI.setUserAvatar(room.myUserId(), email);
  1170. sendEmail(this.commands.defaults.EMAIL, email);
  1171. });
  1172. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  1173. APP.UI.setUserAvatar(data.attributes.id, data.value);
  1174. });
  1175. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  1176. nickname = nickname.trim();
  1177. if (nickname === APP.settings.getDisplayName()) {
  1178. return;
  1179. }
  1180. APP.settings.setDisplayName(nickname);
  1181. room.setDisplayName(nickname);
  1182. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  1183. });
  1184. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1185. (startAudioMuted, startVideoMuted) => {
  1186. room.setStartMutedPolicy({
  1187. audio: startAudioMuted,
  1188. video: startVideoMuted
  1189. });
  1190. }
  1191. );
  1192. room.on(
  1193. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1194. ({ audio, video }) => {
  1195. APP.UI.onStartMutedChanged(audio, video);
  1196. }
  1197. );
  1198. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1199. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1200. && APP.UI.notifyInitiallyMuted();
  1201. });
  1202. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1203. APP.UI.inviteParticipants(
  1204. roomUrl,
  1205. APP.conference.roomName,
  1206. roomLocker.password,
  1207. APP.settings.getDisplayName()
  1208. );
  1209. });
  1210. room.on(
  1211. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1212. APP.UI.updateDevicesAvailability(id, devices);
  1213. }
  1214. );
  1215. // call hangup
  1216. APP.UI.addListener(UIEvents.HANGUP, () => {
  1217. hangup(true);
  1218. });
  1219. // logout
  1220. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1221. AuthHandler.logout(room).then(function (url) {
  1222. if (url) {
  1223. window.location.href = url;
  1224. } else {
  1225. hangup(true);
  1226. }
  1227. });
  1228. });
  1229. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1230. room.dial(sipNumber);
  1231. });
  1232. // Starts or stops the recording for the conference.
  1233. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1234. room.toggleRecording(options);
  1235. });
  1236. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1237. room.setSubject(topic);
  1238. });
  1239. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1240. APP.UI.setSubject(subject);
  1241. });
  1242. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1243. room.kickParticipant(id);
  1244. });
  1245. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1246. room.muteParticipant(id);
  1247. });
  1248. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1249. AuthHandler.authenticate(room);
  1250. });
  1251. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1252. room.selectParticipant(id);
  1253. });
  1254. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1255. var smallVideoId = smallVideo.getId();
  1256. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1257. && !APP.conference.isLocalId(smallVideoId))
  1258. if (isPinned)
  1259. room.pinParticipant(smallVideoId);
  1260. // When the library starts supporting multiple pins we would
  1261. // pass the isPinned parameter together with the identifier,
  1262. // but currently we send null to indicate that we unpin the
  1263. // last pinned.
  1264. else
  1265. room.pinParticipant(null);
  1266. });
  1267. APP.UI.addListener(
  1268. UIEvents.VIDEO_DEVICE_CHANGED,
  1269. (cameraDeviceId) => {
  1270. createLocalTracks(['video'])
  1271. .then(([stream]) => {
  1272. this.useVideoStream(stream);
  1273. console.log('switched local video device');
  1274. APP.settings.setCameraDeviceId(cameraDeviceId);
  1275. })
  1276. .catch((err) => {
  1277. APP.UI.showDeviceErrorDialog(null, err);
  1278. APP.UI.setSelectedCameraFromSettings();
  1279. });
  1280. }
  1281. );
  1282. APP.UI.addListener(
  1283. UIEvents.AUDIO_DEVICE_CHANGED,
  1284. (micDeviceId) => {
  1285. createLocalTracks(['audio'])
  1286. .then(([stream]) => {
  1287. this.useAudioStream(stream);
  1288. console.log('switched local audio device');
  1289. APP.settings.setMicDeviceId(micDeviceId);
  1290. })
  1291. .catch((err) => {
  1292. APP.UI.showDeviceErrorDialog(err, null);
  1293. APP.UI.setSelectedMicFromSettings();
  1294. });
  1295. }
  1296. );
  1297. APP.UI.addListener(
  1298. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1299. (audioOutputDeviceId) => {
  1300. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1301. .then(() => console.log('changed audio output device'))
  1302. .catch((err) => {
  1303. console.warn('Failed to change audio output device. ' +
  1304. 'Default or previously set audio output device ' +
  1305. 'will be used instead.', err);
  1306. APP.UI.setSelectedAudioOutputFromSettings();
  1307. });
  1308. }
  1309. );
  1310. APP.UI.addListener(
  1311. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1312. );
  1313. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1314. (url, state, time, isMuted, volume) => {
  1315. // send start and stop commands once, and remove any updates
  1316. // that had left
  1317. if (state === 'stop' || state === 'start' || state === 'playing') {
  1318. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1319. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1320. value: url,
  1321. attributes: {
  1322. state: state,
  1323. time: time,
  1324. muted: isMuted,
  1325. volume: volume
  1326. }
  1327. });
  1328. }
  1329. else {
  1330. // in case of paused, in order to allow late users to join
  1331. // paused
  1332. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1333. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1334. value: url,
  1335. attributes: {
  1336. state: state,
  1337. time: time,
  1338. muted: isMuted,
  1339. volume: volume
  1340. }
  1341. });
  1342. }
  1343. });
  1344. room.addCommandListener(
  1345. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1346. if (attributes.state === 'stop') {
  1347. APP.UI.onSharedVideoStop(id, attributes);
  1348. }
  1349. else if (attributes.state === 'start') {
  1350. APP.UI.onSharedVideoStart(id, value, attributes);
  1351. }
  1352. else if (attributes.state === 'playing'
  1353. || attributes.state === 'pause') {
  1354. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1355. }
  1356. });
  1357. },
  1358. /**
  1359. * Adss any room listener.
  1360. * @param eventName one of the ConferenceEvents
  1361. * @param callBack the function to be called when the event occurs
  1362. */
  1363. addConferenceListener(eventName, callBack) {
  1364. room.on(eventName, callBack);
  1365. }
  1366. };