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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  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 || [])
  532. .concat(videoTracks || []);
  533. });
  534. } else {
  535. promise = createAudioTrack();
  536. }
  537. } else if (videoRequested && cameraDeviceId !== null) {
  538. promise = createVideoTrack();
  539. } else {
  540. promise = Promise.resolve([]);
  541. }
  542. return promise
  543. .then(onTracksCreated);
  544. function createAudioTrack(showError) {
  545. return createLocalTracks(['audio'], null, micDeviceId)
  546. .catch(err => {
  547. audioTrackCreationError = err;
  548. if (showError) {
  549. APP.UI.showDeviceErrorDialog(err, null);
  550. }
  551. return [];
  552. });
  553. }
  554. function createVideoTrack(showError) {
  555. return createLocalTracks(
  556. ['video'], cameraDeviceId, null)
  557. .catch(err => {
  558. videoTrackCreationError = err;
  559. if (showError) {
  560. APP.UI.showDeviceErrorDialog(null, err);
  561. }
  562. return [];
  563. });
  564. }
  565. }
  566. function onTracksCreated(tracks) {
  567. return Promise.all((tracks || []).map(track => {
  568. if (track.isAudioTrack()) {
  569. let audioWasMuted = self.audioMuted;
  570. return self.useAudioStream(track).then(() => {
  571. console.log('switched local audio');
  572. // If we plugged-in new device (and switched to
  573. // it), but video was muted before, or we
  574. // unplugged current device and selected new
  575. // one, then mute new video track.
  576. if (audioWasMuted ||
  577. currentAudioInputDevices.length >
  578. availableAudioInputDevices.length) {
  579. muteLocalAudio(true);
  580. }
  581. });
  582. } else if (track.isVideoTrack()) {
  583. let videoWasMuted = self.videoMuted;
  584. return self.useVideoStream(track).then(() => {
  585. console.log('switched local video');
  586. // TODO: maybe make video large if we
  587. // are not in conference yet
  588. // If we plugged-in new device (and switched to
  589. // it), but video was muted before, or we
  590. // unplugged current device and selected new
  591. // one, then mute new video track.
  592. if (videoWasMuted ||
  593. (currentVideoInputDevices.length >
  594. availableVideoInputDevices.length)) {
  595. muteLocalVideo(true);
  596. }
  597. });
  598. } else {
  599. console.error("Ignored not an audio nor a "
  600. + "video track: ", track);
  601. return Promise.resolve();
  602. }
  603. }));
  604. }
  605. }
  606. });
  607. },
  608. /**
  609. * Check if id is id of the local user.
  610. * @param {string} id id to check
  611. * @returns {boolean}
  612. */
  613. isLocalId (id) {
  614. return this.localId === id;
  615. },
  616. /**
  617. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  618. * @param mute true for mute and false for unmute.
  619. */
  620. muteAudio (mute) {
  621. muteLocalAudio(mute);
  622. },
  623. /**
  624. * Returns whether local audio is muted or not.
  625. * @returns {boolean}
  626. */
  627. isLocalAudioMuted() {
  628. return this.audioMuted;
  629. },
  630. /**
  631. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  632. */
  633. toggleAudioMuted () {
  634. this.muteAudio(!this.audioMuted);
  635. },
  636. /**
  637. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  638. * @param mute true for mute and false for unmute.
  639. */
  640. muteVideo (mute) {
  641. muteLocalVideo(mute);
  642. },
  643. /**
  644. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  645. */
  646. toggleVideoMuted () {
  647. this.muteVideo(!this.videoMuted);
  648. },
  649. /**
  650. * Retrieve list of conference participants (without local user).
  651. * @returns {JitsiParticipant[]}
  652. */
  653. listMembers () {
  654. return room.getParticipants();
  655. },
  656. /**
  657. * Retrieve list of ids of conference participants (without local user).
  658. * @returns {string[]}
  659. */
  660. listMembersIds () {
  661. return room.getParticipants().map(p => p.getId());
  662. },
  663. /**
  664. * Checks whether the participant identified by id is a moderator.
  665. * @id id to search for participant
  666. * @return {boolean} whether the participant is moderator
  667. */
  668. isParticipantModerator (id) {
  669. let user = room.getParticipantById(id);
  670. return user && user.isModerator();
  671. },
  672. /**
  673. * Check if SIP is supported.
  674. * @returns {boolean}
  675. */
  676. sipGatewayEnabled () {
  677. return room.isSIPCallingSupported();
  678. },
  679. get membersCount () {
  680. return room.getParticipants().length + 1;
  681. },
  682. /**
  683. * Returns true if the callstats integration is enabled, otherwise returns
  684. * false.
  685. *
  686. * @returns true if the callstats integration is enabled, otherwise returns
  687. * false.
  688. */
  689. isCallstatsEnabled () {
  690. return room.isCallstatsEnabled();
  691. },
  692. /**
  693. * Sends the given feedback through CallStats if enabled.
  694. *
  695. * @param overallFeedback an integer between 1 and 5 indicating the
  696. * user feedback
  697. * @param detailedFeedback detailed feedback from the user. Not yet used
  698. */
  699. sendFeedback (overallFeedback, detailedFeedback) {
  700. return room.sendFeedback (overallFeedback, detailedFeedback);
  701. },
  702. // used by torture currently
  703. isJoined () {
  704. return this._room
  705. && this._room.isJoined();
  706. },
  707. getConnectionState () {
  708. return this._room
  709. && this._room.getConnectionState();
  710. },
  711. getMyUserId () {
  712. return this._room
  713. && this._room.myUserId();
  714. },
  715. /**
  716. * Indicates if recording is supported in this conference.
  717. */
  718. isRecordingSupported() {
  719. return this._room && this._room.isRecordingSupported();
  720. },
  721. /**
  722. * Returns the recording state or undefined if the room is not defined.
  723. */
  724. getRecordingState() {
  725. return (this._room) ? this._room.getRecordingState() : undefined;
  726. },
  727. /**
  728. * Will be filled with values only when config.debug is enabled.
  729. * Its used by torture to check audio levels.
  730. */
  731. audioLevelsMap: {},
  732. /**
  733. * Returns the stored audio level (stored only if config.debug is enabled)
  734. * @param id the id for the user audio level to return (the id value is
  735. * returned for the participant using getMyUserId() method)
  736. */
  737. getPeerSSRCAudioLevel (id) {
  738. return this.audioLevelsMap[id];
  739. },
  740. /**
  741. * @return {number} the number of participants in the conference with at
  742. * least one track.
  743. */
  744. getNumberOfParticipantsWithTracks() {
  745. return this._room.getParticipants()
  746. .filter((p) => p.getTracks().length > 0)
  747. .length;
  748. },
  749. /**
  750. * Returns the stats.
  751. */
  752. getStats() {
  753. return ConnectionQuality.getStats();
  754. },
  755. // end used by torture
  756. getLogs () {
  757. return room.getLogs();
  758. },
  759. /**
  760. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  761. * desire to keep room private to this instance and (2) the need of other
  762. * modules to send and receive commands to and from participants.
  763. * Eventually, this instance remains in control with respect to the
  764. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  765. * JitsiConference) is to be used in the implementation of the Command(s)
  766. * API of this instance.
  767. */
  768. commands: {
  769. /**
  770. * Known custom conference commands.
  771. */
  772. defaults: {
  773. CONNECTION_QUALITY: "stats",
  774. EMAIL: "email",
  775. ETHERPAD: "etherpad",
  776. SHARED_VIDEO: "shared-video",
  777. CUSTOM_ROLE: "custom-role"
  778. },
  779. /**
  780. * Receives notifications from other participants about commands aka
  781. * custom events (sent by sendCommand or sendCommandOnce methods).
  782. * @param command {String} the name of the command
  783. * @param handler {Function} handler for the command
  784. */
  785. addCommandListener () {
  786. room.addCommandListener.apply(room, arguments);
  787. },
  788. /**
  789. * Removes command.
  790. * @param name {String} the name of the command.
  791. */
  792. removeCommand () {
  793. room.removeCommand.apply(room, arguments);
  794. },
  795. /**
  796. * Sends command.
  797. * @param name {String} the name of the command.
  798. * @param values {Object} with keys and values that will be sent.
  799. */
  800. sendCommand () {
  801. room.sendCommand.apply(room, arguments);
  802. },
  803. /**
  804. * Sends command one time.
  805. * @param name {String} the name of the command.
  806. * @param values {Object} with keys and values that will be sent.
  807. */
  808. sendCommandOnce () {
  809. room.sendCommandOnce.apply(room, arguments);
  810. }
  811. },
  812. _createRoom (localTracks) {
  813. room = connection.initJitsiConference(APP.conference.roomName,
  814. this._getConferenceOptions());
  815. this.localId = room.myUserId();
  816. localTracks.forEach((track) => {
  817. if (track.isAudioTrack()) {
  818. this.useAudioStream(track);
  819. } else if (track.isVideoTrack()) {
  820. this.useVideoStream(track);
  821. } else {
  822. console.error(
  823. "Ignored not an audio nor a video track: ", track);
  824. }
  825. });
  826. roomLocker = createRoomLocker(room);
  827. this._room = room; // FIXME do not use this
  828. let email = APP.settings.getEmail();
  829. email && sendEmail(this.commands.defaults.EMAIL, email);
  830. let nick = APP.settings.getDisplayName();
  831. if (config.useNicks && !nick) {
  832. nick = APP.UI.askForNickname();
  833. APP.settings.setDisplayName(nick);
  834. }
  835. nick && room.setDisplayName(nick);
  836. this._setupListeners();
  837. },
  838. _getConferenceOptions() {
  839. let options = config;
  840. if(config.enableRecording && !config.recordingType) {
  841. options.recordingType = (config.hosts &&
  842. (typeof config.hosts.jirecon != "undefined"))?
  843. "jirecon" : "colibri";
  844. }
  845. return options;
  846. },
  847. /**
  848. * Start using provided video stream.
  849. * Stops previous video stream.
  850. * @param {JitsiLocalTrack} [stream] new stream to use or null
  851. * @returns {Promise}
  852. */
  853. useVideoStream (stream) {
  854. let promise = Promise.resolve();
  855. if (localVideo) {
  856. // this calls room.removeTrack internally
  857. // so we don't need to remove it manually
  858. promise = localVideo.dispose();
  859. }
  860. localVideo = stream;
  861. return promise.then(function () {
  862. if (stream) {
  863. return room.addTrack(stream);
  864. }
  865. }).then(() => {
  866. if (stream) {
  867. this.videoMuted = stream.isMuted();
  868. this.isSharingScreen = stream.videoType === 'desktop';
  869. APP.UI.addLocalStream(stream);
  870. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  871. } else {
  872. this.videoMuted = false;
  873. this.isSharingScreen = false;
  874. }
  875. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  876. APP.UI.updateDesktopSharingButtons();
  877. });
  878. },
  879. /**
  880. * Start using provided audio stream.
  881. * Stops previous audio stream.
  882. * @param {JitsiLocalTrack} [stream] new stream to use or null
  883. * @returns {Promise}
  884. */
  885. useAudioStream (stream) {
  886. let promise = Promise.resolve();
  887. if (localAudio) {
  888. // this calls room.removeTrack internally
  889. // so we don't need to remove it manually
  890. promise = localAudio.dispose();
  891. }
  892. localAudio = stream;
  893. return promise.then(function () {
  894. if (stream) {
  895. return room.addTrack(stream);
  896. }
  897. }).then(() => {
  898. if (stream) {
  899. this.audioMuted = stream.isMuted();
  900. APP.UI.addLocalStream(stream);
  901. } else {
  902. this.audioMuted = false;
  903. }
  904. APP.UI.enableMicrophoneButton();
  905. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  906. });
  907. },
  908. videoSwitchInProgress: false,
  909. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  910. if (this.videoSwitchInProgress) {
  911. console.warn("Switch in progress.");
  912. return;
  913. }
  914. if (!this.isDesktopSharingEnabled) {
  915. console.warn("Cannot toggle screen sharing: not supported.");
  916. return;
  917. }
  918. this.videoSwitchInProgress = true;
  919. if (shareScreen) {
  920. createLocalTracks(['desktop']).then(([stream]) => {
  921. stream.on(
  922. TrackEvents.LOCAL_TRACK_STOPPED,
  923. () => {
  924. // if stream was stopped during screensharing session
  925. // then we should switch to video
  926. // otherwise we stopped it because we already switched
  927. // to video, so nothing to do here
  928. if (this.isSharingScreen) {
  929. this.toggleScreenSharing(false);
  930. }
  931. }
  932. );
  933. return this.useVideoStream(stream);
  934. }).then(() => {
  935. this.videoSwitchInProgress = false;
  936. console.log('sharing local desktop');
  937. }).catch((err) => {
  938. this.videoSwitchInProgress = false;
  939. this.toggleScreenSharing(false);
  940. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  941. return;
  942. }
  943. console.error('failed to share local desktop', err);
  944. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  945. APP.UI.showExtensionRequiredDialog(
  946. config.desktopSharingFirefoxExtensionURL
  947. );
  948. return;
  949. }
  950. // Handling:
  951. // TrackErrors.PERMISSION_DENIED
  952. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  953. // TrackErrors.GENERAL
  954. // and any other
  955. let dialogTxt;
  956. let dialogTitle;
  957. if (err.name === TrackErrors.PERMISSION_DENIED) {
  958. dialogTxt = APP.translation.generateTranslationHTML(
  959. "dialog.screenSharingPermissionDeniedError");
  960. dialogTitle = APP.translation.generateTranslationHTML(
  961. "dialog.error");
  962. } else {
  963. dialogTxt = APP.translation.generateTranslationHTML(
  964. "dialog.failtoinstall");
  965. dialogTitle = APP.translation.generateTranslationHTML(
  966. "dialog.permissionDenied");
  967. }
  968. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  969. });
  970. } else {
  971. createLocalTracks(['video']).then(
  972. ([stream]) => this.useVideoStream(stream)
  973. ).then(() => {
  974. this.videoSwitchInProgress = false;
  975. console.log('sharing local video');
  976. }).catch((err) => {
  977. this.useVideoStream(null);
  978. this.videoSwitchInProgress = false;
  979. console.error('failed to share local video', err);
  980. });
  981. }
  982. },
  983. /**
  984. * Setup interaction between conference and UI.
  985. */
  986. _setupListeners () {
  987. // add local streams when joined to the conference
  988. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  989. APP.UI.mucJoined();
  990. });
  991. room.on(
  992. ConferenceEvents.AUTH_STATUS_CHANGED,
  993. function (authEnabled, authLogin) {
  994. APP.UI.updateAuthInfo(authEnabled, authLogin);
  995. }
  996. );
  997. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  998. if (user.isHidden())
  999. return;
  1000. console.log('USER %s connnected', id, user);
  1001. APP.API.notifyUserJoined(id);
  1002. APP.UI.addUser(id, user.getDisplayName());
  1003. // check the roles for the new user and reflect them
  1004. APP.UI.updateUserRole(user);
  1005. });
  1006. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1007. console.log('USER %s LEFT', id, user);
  1008. APP.API.notifyUserLeft(id);
  1009. APP.UI.removeUser(id, user.getDisplayName());
  1010. APP.UI.onSharedVideoStop(id);
  1011. });
  1012. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1013. if (this.isLocalId(id)) {
  1014. console.info(`My role changed, new role: ${role}`);
  1015. this.isModerator = room.isModerator();
  1016. APP.UI.updateLocalRole(room.isModerator());
  1017. } else {
  1018. let user = room.getParticipantById(id);
  1019. if (user) {
  1020. APP.UI.updateUserRole(user);
  1021. }
  1022. }
  1023. });
  1024. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1025. if(!track || track.isLocal())
  1026. return;
  1027. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1028. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1029. });
  1030. APP.UI.addRemoteStream(track);
  1031. });
  1032. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1033. if(!track || track.isLocal())
  1034. return;
  1035. APP.UI.removeRemoteStream(track);
  1036. });
  1037. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1038. if(!track)
  1039. return;
  1040. const handler = (track.getType() === "audio")?
  1041. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1042. let id;
  1043. const mute = track.isMuted();
  1044. if(track.isLocal()){
  1045. id = this.localId;
  1046. if(track.getType() === "audio") {
  1047. this.audioMuted = mute;
  1048. } else {
  1049. this.videoMuted = mute;
  1050. }
  1051. } else {
  1052. id = track.getParticipantId();
  1053. }
  1054. handler(id , mute);
  1055. });
  1056. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1057. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1058. lvl = 0;
  1059. }
  1060. if(config.debug)
  1061. {
  1062. this.audioLevelsMap[id] = lvl;
  1063. if(config.debugAudioLevels)
  1064. console.log("AudioLevel:" + id + "/" + lvl);
  1065. }
  1066. APP.UI.setAudioLevel(id, lvl);
  1067. });
  1068. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1069. //FIXME
  1070. if (config.muteLocalVideoIfNotInLastN) {
  1071. // TODO mute or unmute if required
  1072. // mark video on UI
  1073. // APP.UI.markVideoMuted(true/false);
  1074. }
  1075. });
  1076. room.on(
  1077. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1078. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1079. });
  1080. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1081. APP.UI.markDominantSpeaker(id);
  1082. });
  1083. if (!interfaceConfig.filmStripOnly) {
  1084. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1085. APP.UI.markVideoInterrupted(true);
  1086. });
  1087. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1088. APP.UI.markVideoInterrupted(false);
  1089. });
  1090. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1091. let nick = getDisplayName(id);
  1092. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1093. APP.UI.addMessage(id, nick, text, ts);
  1094. });
  1095. }
  1096. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1097. APP.API.notifyDisplayNameChanged(id, displayName);
  1098. APP.UI.changeDisplayName(id, displayName);
  1099. });
  1100. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1101. console.log("Received recorder status change: ", status, error);
  1102. APP.UI.updateRecordingState(status);
  1103. });
  1104. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1105. APP.UI.updateUserStatus(id, status);
  1106. });
  1107. room.on(ConferenceEvents.KICKED, () => {
  1108. APP.UI.hideStats();
  1109. APP.UI.notifyKicked();
  1110. // FIXME close
  1111. });
  1112. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1113. APP.UI.updateDTMFSupport(isDTMFSupported);
  1114. });
  1115. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1116. if (room.isModerator()) {
  1117. let promise = roomLocker.isLocked
  1118. ? roomLocker.askToUnlock()
  1119. : roomLocker.askToLock();
  1120. promise.then(() => {
  1121. APP.UI.markRoomLocked(roomLocker.isLocked);
  1122. });
  1123. } else {
  1124. roomLocker.notifyModeratorRequired();
  1125. }
  1126. });
  1127. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1128. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1129. if (!interfaceConfig.filmStripOnly) {
  1130. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1131. APP.API.notifySendingChatMessage(message);
  1132. room.sendTextMessage(message);
  1133. });
  1134. }
  1135. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1136. ConnectionQuality.updateLocalStats(stats);
  1137. });
  1138. ConnectionQuality.addListener(
  1139. CQEvents.LOCALSTATS_UPDATED,
  1140. (percent, stats) => {
  1141. APP.UI.updateLocalStats(percent, stats);
  1142. // send local stats to other users
  1143. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  1144. {
  1145. children: ConnectionQuality.convertToMUCStats(stats),
  1146. attributes: {
  1147. xmlns: 'http://jitsi.org/jitmeet/stats'
  1148. }
  1149. });
  1150. }
  1151. );
  1152. // listen to remote stats
  1153. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  1154. (values, from) => {
  1155. ConnectionQuality.updateRemoteStats(from, values);
  1156. });
  1157. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1158. (id, percent, stats) => {
  1159. APP.UI.updateRemoteStats(id, percent, stats);
  1160. });
  1161. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1162. APP.UI.initEtherpad(value);
  1163. });
  1164. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  1165. email = email.trim();
  1166. if (email === APP.settings.getEmail()) {
  1167. return;
  1168. }
  1169. APP.settings.setEmail(email);
  1170. APP.UI.setUserAvatar(room.myUserId(), email);
  1171. sendEmail(this.commands.defaults.EMAIL, email);
  1172. });
  1173. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  1174. APP.UI.setUserAvatar(data.attributes.id, data.value);
  1175. });
  1176. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  1177. nickname = nickname.trim();
  1178. if (nickname === APP.settings.getDisplayName()) {
  1179. return;
  1180. }
  1181. APP.settings.setDisplayName(nickname);
  1182. room.setDisplayName(nickname);
  1183. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  1184. });
  1185. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1186. (startAudioMuted, startVideoMuted) => {
  1187. room.setStartMutedPolicy({
  1188. audio: startAudioMuted,
  1189. video: startVideoMuted
  1190. });
  1191. }
  1192. );
  1193. room.on(
  1194. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1195. ({ audio, video }) => {
  1196. APP.UI.onStartMutedChanged(audio, video);
  1197. }
  1198. );
  1199. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1200. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1201. && APP.UI.notifyInitiallyMuted();
  1202. });
  1203. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1204. APP.UI.inviteParticipants(
  1205. roomUrl,
  1206. APP.conference.roomName,
  1207. roomLocker.password,
  1208. APP.settings.getDisplayName()
  1209. );
  1210. });
  1211. room.on(
  1212. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1213. APP.UI.updateDevicesAvailability(id, devices);
  1214. }
  1215. );
  1216. // call hangup
  1217. APP.UI.addListener(UIEvents.HANGUP, () => {
  1218. hangup(true);
  1219. });
  1220. // logout
  1221. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1222. AuthHandler.logout(room).then(function (url) {
  1223. if (url) {
  1224. window.location.href = url;
  1225. } else {
  1226. hangup(true);
  1227. }
  1228. });
  1229. });
  1230. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1231. room.dial(sipNumber);
  1232. });
  1233. // Starts or stops the recording for the conference.
  1234. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1235. room.toggleRecording(options);
  1236. });
  1237. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1238. room.setSubject(topic);
  1239. });
  1240. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1241. APP.UI.setSubject(subject);
  1242. });
  1243. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1244. room.kickParticipant(id);
  1245. });
  1246. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1247. room.muteParticipant(id);
  1248. });
  1249. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1250. AuthHandler.authenticate(room);
  1251. });
  1252. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1253. room.selectParticipant(id);
  1254. });
  1255. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1256. var smallVideoId = smallVideo.getId();
  1257. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1258. && !APP.conference.isLocalId(smallVideoId))
  1259. if (isPinned)
  1260. room.pinParticipant(smallVideoId);
  1261. // When the library starts supporting multiple pins we would
  1262. // pass the isPinned parameter together with the identifier,
  1263. // but currently we send null to indicate that we unpin the
  1264. // last pinned.
  1265. else
  1266. room.pinParticipant(null);
  1267. });
  1268. APP.UI.addListener(
  1269. UIEvents.VIDEO_DEVICE_CHANGED,
  1270. (cameraDeviceId) => {
  1271. createLocalTracks(['video'])
  1272. .then(([stream]) => {
  1273. this.useVideoStream(stream);
  1274. console.log('switched local video device');
  1275. APP.settings.setCameraDeviceId(cameraDeviceId);
  1276. })
  1277. .catch((err) => {
  1278. APP.UI.showDeviceErrorDialog(null, err);
  1279. APP.UI.setSelectedCameraFromSettings();
  1280. });
  1281. }
  1282. );
  1283. APP.UI.addListener(
  1284. UIEvents.AUDIO_DEVICE_CHANGED,
  1285. (micDeviceId) => {
  1286. createLocalTracks(['audio'])
  1287. .then(([stream]) => {
  1288. this.useAudioStream(stream);
  1289. console.log('switched local audio device');
  1290. APP.settings.setMicDeviceId(micDeviceId);
  1291. })
  1292. .catch((err) => {
  1293. APP.UI.showDeviceErrorDialog(err, null);
  1294. APP.UI.setSelectedMicFromSettings();
  1295. });
  1296. }
  1297. );
  1298. APP.UI.addListener(
  1299. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1300. (audioOutputDeviceId) => {
  1301. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1302. .then(() => console.log('changed audio output device'))
  1303. .catch((err) => {
  1304. console.warn('Failed to change audio output device. ' +
  1305. 'Default or previously set audio output device ' +
  1306. 'will be used instead.', err);
  1307. APP.UI.setSelectedAudioOutputFromSettings();
  1308. });
  1309. }
  1310. );
  1311. APP.UI.addListener(
  1312. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1313. );
  1314. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1315. (url, state, time, isMuted, volume) => {
  1316. // send start and stop commands once, and remove any updates
  1317. // that had left
  1318. if (state === 'stop' || state === 'start' || state === 'playing') {
  1319. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1320. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1321. value: url,
  1322. attributes: {
  1323. state: state,
  1324. time: time,
  1325. muted: isMuted,
  1326. volume: volume
  1327. }
  1328. });
  1329. }
  1330. else {
  1331. // in case of paused, in order to allow late users to join
  1332. // paused
  1333. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1334. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1335. value: url,
  1336. attributes: {
  1337. state: state,
  1338. time: time,
  1339. muted: isMuted,
  1340. volume: volume
  1341. }
  1342. });
  1343. }
  1344. });
  1345. room.addCommandListener(
  1346. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1347. if (attributes.state === 'stop') {
  1348. APP.UI.onSharedVideoStop(id, attributes);
  1349. }
  1350. else if (attributes.state === 'start') {
  1351. APP.UI.onSharedVideoStart(id, value, attributes);
  1352. }
  1353. else if (attributes.state === 'playing'
  1354. || attributes.state === 'pause') {
  1355. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1356. }
  1357. });
  1358. },
  1359. /**
  1360. * Adss any room listener.
  1361. * @param eventName one of the ConferenceEvents
  1362. * @param callBack the function to be called when the event occurs
  1363. */
  1364. addConferenceListener(eventName, callBack) {
  1365. room.on(eventName, callBack);
  1366. }
  1367. };