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 50KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. return JitsiMeetJS.init(config).then(() => {
  337. return Promise.all([
  338. // try to retrieve audio and video
  339. createLocalTracks(['audio', 'video'])
  340. // if failed then try to retrieve only audio
  341. .catch(() => createLocalTracks(['audio']))
  342. // if audio also failed then just return empty array
  343. .catch(() => []),
  344. connect(options.roomName)
  345. ]);
  346. }).then(([tracks, con]) => {
  347. console.log('initialized with %s local tracks', tracks.length);
  348. APP.connection = connection = con;
  349. this._createRoom(tracks);
  350. this.isDesktopSharingEnabled =
  351. JitsiMeetJS.isDesktopSharingEnabled();
  352. // if user didn't give access to mic or camera or doesn't have
  353. // them at all, we disable corresponding toolbar buttons
  354. if (!tracks.find((t) => t.isAudioTrack())) {
  355. APP.UI.disableMicrophoneButton();
  356. }
  357. if (!tracks.find((t) => t.isVideoTrack())) {
  358. APP.UI.disableCameraButton();
  359. }
  360. // update list of available devices
  361. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  362. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  363. JitsiMeetJS.mediaDevices.enumerateDevices(function(devices) {
  364. // Ugly way to synchronize real device IDs with local
  365. // storage and settings menu. This is a workaround until
  366. // getConstraints() method will be implemented in browsers.
  367. if (localAudio) {
  368. localAudio._setRealDeviceIdFromDeviceList(devices);
  369. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  370. }
  371. if (localVideo) {
  372. localVideo._setRealDeviceIdFromDeviceList(devices);
  373. APP.settings.setCameraDeviceId(
  374. localVideo.getDeviceId());
  375. }
  376. setCurrentMediaDevices(devices);
  377. APP.UI.onAvailableDevicesChanged(devices);
  378. });
  379. JitsiMeetJS.mediaDevices.addEventListener(
  380. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  381. (devices) => {
  382. // Just defer callback until other event callbacks are
  383. // processed.
  384. window.setTimeout(() => {
  385. checkLocalDevicesAfterDeviceListChanged(devices)
  386. .then(() => {
  387. setCurrentMediaDevices(devices);
  388. APP.UI.onAvailableDevicesChanged(devices);
  389. });
  390. }, 0);
  391. });
  392. }
  393. if (config.iAmRecorder)
  394. this.recorder = new Recorder();
  395. // XXX The API will take care of disconnecting from the XMPP server
  396. // (and, thus, leaving the room) on unload.
  397. return new Promise((resolve, reject) => {
  398. (new ConferenceConnector(resolve, reject)).connect();
  399. });
  400. function checkAudioOutputDeviceAfterDeviceListChanged(newDevices) {
  401. if (!JitsiMeetJS.mediaDevices
  402. .isDeviceChangeAvailable('output')) {
  403. return;
  404. }
  405. var selectedAudioOutputDeviceId =
  406. APP.settings.getAudioOutputDeviceId(),
  407. availableAudioOutputDevices = newDevices.filter(d => {
  408. return d.kind === 'audiooutput';
  409. });
  410. if (selectedAudioOutputDeviceId !== 'default' &&
  411. !availableAudioOutputDevices.find(d =>
  412. d.deviceId === selectedAudioOutputDeviceId)) {
  413. APP.settings.setAudioOutputDeviceId('default');
  414. }
  415. }
  416. function checkLocalDevicesAfterDeviceListChanged(newDevices) {
  417. // Event handler can be fire before direct enumerateDevices()
  418. // call, so handle this situation here.
  419. if (!currentAudioInputDevices && !currentVideoInputDevices) {
  420. setCurrentMediaDevices(newDevices);
  421. }
  422. checkAudioOutputDeviceAfterDeviceListChanged(newDevices);
  423. let availableAudioInputDevices = newDevices.filter(
  424. d => d.kind === 'audioinput'),
  425. availableVideoInputDevices = newDevices.filter(
  426. d => d.kind === 'videoinput'),
  427. selectedAudioInputDeviceId = APP.settings.getMicDeviceId(),
  428. selectedVideoInputDeviceId =
  429. APP.settings.getCameraDeviceId(),
  430. selectedAudioInputDevice = availableAudioInputDevices.find(
  431. d => d.deviceId === selectedAudioInputDeviceId),
  432. selectedVideoInputDevice = availableVideoInputDevices.find(
  433. d => d.deviceId === selectedVideoInputDeviceId),
  434. tracksToCreate = [],
  435. micIdToUse = null,
  436. cameraIdToUse = null;
  437. // Here we handle case when no device was initially plugged, but
  438. // then it's connected OR new device was connected when previous
  439. // track has ended.
  440. if (!localAudio || localAudio.disposed || localAudio.isEnded()){
  441. if (availableAudioInputDevices.length
  442. && availableAudioInputDevices[0].label !== '') {
  443. tracksToCreate.push('audio');
  444. micIdToUse = availableAudioInputDevices[0].deviceId;
  445. } else {
  446. APP.UI.disableMicrophoneButton();
  447. }
  448. }
  449. if ((!localVideo || localVideo.disposed || localVideo.isEnded())
  450. && !self.isSharingScreen){
  451. if (availableVideoInputDevices.length
  452. && availableVideoInputDevices[0].label !== '') {
  453. tracksToCreate.push('video');
  454. cameraIdToUse = availableVideoInputDevices[0].deviceId;
  455. } else {
  456. APP.UI.disableCameraButton();
  457. }
  458. }
  459. if (localAudio && !localAudio.disposed && !localAudio.isEnded()
  460. && selectedAudioInputDevice
  461. && selectedAudioInputDeviceId !== localAudio.getDeviceId()
  462. && tracksToCreate.indexOf('audio') === -1) {
  463. tracksToCreate.push('audio');
  464. micIdToUse = selectedAudioInputDeviceId;
  465. }
  466. if (localVideo && !localVideo.disposed && !localVideo.isEnded()
  467. && selectedVideoInputDevice
  468. && selectedVideoInputDeviceId !== localVideo.getDeviceId()
  469. && tracksToCreate.indexOf('video') === -1
  470. && !self.isSharingScreen) {
  471. tracksToCreate.push('video');
  472. cameraIdToUse = selectedVideoInputDeviceId;
  473. }
  474. if (tracksToCreate.length) {
  475. return createNewTracks(
  476. tracksToCreate, cameraIdToUse, micIdToUse);
  477. } else {
  478. return Promise.resolve();
  479. }
  480. function createNewTracks(type, cameraDeviceId, micDeviceId) {
  481. return createLocalTracks(type, cameraDeviceId, micDeviceId)
  482. .then(onTracksCreated)
  483. .catch(() => {
  484. // if we tried to create both audio and video tracks
  485. // at once and failed, let's try again only with
  486. // audio. Such situation may happen in case if we
  487. // granted access only to microphone, but not to
  488. // camera.
  489. if (type.indexOf('audio') !== -1
  490. && type.indexOf('video') !== -1) {
  491. return createLocalTracks(['audio'], null,
  492. micDeviceId);
  493. }
  494. })
  495. .then(onTracksCreated)
  496. .catch(() => {
  497. // if we tried to create both audio and video tracks
  498. // at once and failed, let's try again only with
  499. // video. Such situation may happen in case if we
  500. // granted access only to camera, but not to
  501. // microphone.
  502. if (type.indexOf('audio') !== -1
  503. && type.indexOf('video') !== -1) {
  504. return createLocalTracks(['video'],
  505. cameraDeviceId,
  506. null);
  507. }
  508. })
  509. .then(onTracksCreated)
  510. .catch(() => {
  511. // can't do anything in this case, so just ignore;
  512. });
  513. }
  514. function onTracksCreated(tracks) {
  515. return Promise.all((tracks || []).map(track => {
  516. if (track.isAudioTrack()) {
  517. let audioWasMuted = self.audioMuted;
  518. return self.useAudioStream(track).then(() => {
  519. console.log('switched local audio');
  520. // If we plugged-in new device (and switched to
  521. // it), but video was muted before, or we
  522. // unplugged current device and selected new
  523. // one, then mute new video track.
  524. if (audioWasMuted ||
  525. currentAudioInputDevices.length >
  526. availableAudioInputDevices.length) {
  527. muteLocalAudio(true);
  528. }
  529. });
  530. } else if (track.isVideoTrack()) {
  531. let videoWasMuted = self.videoMuted;
  532. return self.useVideoStream(track).then(() => {
  533. console.log('switched local video');
  534. // TODO: maybe make video large if we
  535. // are not in conference yet
  536. // If we plugged-in new device (and switched to
  537. // it), but video was muted before, or we
  538. // unplugged current device and selected new
  539. // one, then mute new video track.
  540. if (videoWasMuted ||
  541. (currentVideoInputDevices.length >
  542. availableVideoInputDevices.length)) {
  543. muteLocalVideo(true);
  544. }
  545. });
  546. } else {
  547. console.error("Ignored not an audio nor a "
  548. + "video track: ", track);
  549. return Promise.resolve();
  550. }
  551. }));
  552. }
  553. }
  554. });
  555. },
  556. /**
  557. * Check if id is id of the local user.
  558. * @param {string} id id to check
  559. * @returns {boolean}
  560. */
  561. isLocalId (id) {
  562. return this.localId === id;
  563. },
  564. /**
  565. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  566. * @param mute true for mute and false for unmute.
  567. */
  568. muteAudio (mute) {
  569. muteLocalAudio(mute);
  570. },
  571. /**
  572. * Returns whether local audio is muted or not.
  573. * @returns {boolean}
  574. */
  575. isLocalAudioMuted() {
  576. return this.audioMuted;
  577. },
  578. /**
  579. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  580. */
  581. toggleAudioMuted () {
  582. this.muteAudio(!this.audioMuted);
  583. },
  584. /**
  585. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  586. * @param mute true for mute and false for unmute.
  587. */
  588. muteVideo (mute) {
  589. muteLocalVideo(mute);
  590. },
  591. /**
  592. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  593. */
  594. toggleVideoMuted () {
  595. this.muteVideo(!this.videoMuted);
  596. },
  597. /**
  598. * Retrieve list of conference participants (without local user).
  599. * @returns {JitsiParticipant[]}
  600. */
  601. listMembers () {
  602. return room.getParticipants();
  603. },
  604. /**
  605. * Retrieve list of ids of conference participants (without local user).
  606. * @returns {string[]}
  607. */
  608. listMembersIds () {
  609. return room.getParticipants().map(p => p.getId());
  610. },
  611. /**
  612. * Checks whether the participant identified by id is a moderator.
  613. * @id id to search for participant
  614. * @return {boolean} whether the participant is moderator
  615. */
  616. isParticipantModerator (id) {
  617. let user = room.getParticipantById(id);
  618. return user && user.isModerator();
  619. },
  620. /**
  621. * Check if SIP is supported.
  622. * @returns {boolean}
  623. */
  624. sipGatewayEnabled () {
  625. return room.isSIPCallingSupported();
  626. },
  627. get membersCount () {
  628. return room.getParticipants().length + 1;
  629. },
  630. /**
  631. * Returns true if the callstats integration is enabled, otherwise returns
  632. * false.
  633. *
  634. * @returns true if the callstats integration is enabled, otherwise returns
  635. * false.
  636. */
  637. isCallstatsEnabled () {
  638. return room.isCallstatsEnabled();
  639. },
  640. /**
  641. * Sends the given feedback through CallStats if enabled.
  642. *
  643. * @param overallFeedback an integer between 1 and 5 indicating the
  644. * user feedback
  645. * @param detailedFeedback detailed feedback from the user. Not yet used
  646. */
  647. sendFeedback (overallFeedback, detailedFeedback) {
  648. return room.sendFeedback (overallFeedback, detailedFeedback);
  649. },
  650. // used by torture currently
  651. isJoined () {
  652. return this._room
  653. && this._room.isJoined();
  654. },
  655. getConnectionState () {
  656. return this._room
  657. && this._room.getConnectionState();
  658. },
  659. getMyUserId () {
  660. return this._room
  661. && this._room.myUserId();
  662. },
  663. /**
  664. * Indicates if recording is supported in this conference.
  665. */
  666. isRecordingSupported() {
  667. return this._room && this._room.isRecordingSupported();
  668. },
  669. /**
  670. * Returns the recording state or undefined if the room is not defined.
  671. */
  672. getRecordingState() {
  673. return (this._room) ? this._room.getRecordingState() : undefined;
  674. },
  675. /**
  676. * Will be filled with values only when config.debug is enabled.
  677. * Its used by torture to check audio levels.
  678. */
  679. audioLevelsMap: {},
  680. /**
  681. * Returns the stored audio level (stored only if config.debug is enabled)
  682. * @param id the id for the user audio level to return (the id value is
  683. * returned for the participant using getMyUserId() method)
  684. */
  685. getPeerSSRCAudioLevel (id) {
  686. return this.audioLevelsMap[id];
  687. },
  688. /**
  689. * @return {number} the number of participants in the conference with at
  690. * least one track.
  691. */
  692. getNumberOfParticipantsWithTracks() {
  693. return this._room.getParticipants()
  694. .filter((p) => p.getTracks().length > 0)
  695. .length;
  696. },
  697. /**
  698. * Returns the stats.
  699. */
  700. getStats() {
  701. return ConnectionQuality.getStats();
  702. },
  703. // end used by torture
  704. getLogs () {
  705. return room.getLogs();
  706. },
  707. /**
  708. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  709. * desire to keep room private to this instance and (2) the need of other
  710. * modules to send and receive commands to and from participants.
  711. * Eventually, this instance remains in control with respect to the
  712. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  713. * JitsiConference) is to be used in the implementation of the Command(s)
  714. * API of this instance.
  715. */
  716. commands: {
  717. /**
  718. * Known custom conference commands.
  719. */
  720. defaults: {
  721. CONNECTION_QUALITY: "stats",
  722. EMAIL: "email",
  723. ETHERPAD: "etherpad",
  724. SHARED_VIDEO: "shared-video",
  725. CUSTOM_ROLE: "custom-role"
  726. },
  727. /**
  728. * Receives notifications from other participants about commands aka
  729. * custom events (sent by sendCommand or sendCommandOnce methods).
  730. * @param command {String} the name of the command
  731. * @param handler {Function} handler for the command
  732. */
  733. addCommandListener () {
  734. room.addCommandListener.apply(room, arguments);
  735. },
  736. /**
  737. * Removes command.
  738. * @param name {String} the name of the command.
  739. */
  740. removeCommand () {
  741. room.removeCommand.apply(room, arguments);
  742. },
  743. /**
  744. * Sends command.
  745. * @param name {String} the name of the command.
  746. * @param values {Object} with keys and values that will be sent.
  747. */
  748. sendCommand () {
  749. room.sendCommand.apply(room, arguments);
  750. },
  751. /**
  752. * Sends command one time.
  753. * @param name {String} the name of the command.
  754. * @param values {Object} with keys and values that will be sent.
  755. */
  756. sendCommandOnce () {
  757. room.sendCommandOnce.apply(room, arguments);
  758. }
  759. },
  760. _createRoom (localTracks) {
  761. room = connection.initJitsiConference(APP.conference.roomName,
  762. this._getConferenceOptions());
  763. this.localId = room.myUserId();
  764. localTracks.forEach((track) => {
  765. if (track.isAudioTrack()) {
  766. this.useAudioStream(track);
  767. } else if (track.isVideoTrack()) {
  768. this.useVideoStream(track);
  769. } else {
  770. console.error(
  771. "Ignored not an audio nor a video track: ", track);
  772. }
  773. });
  774. roomLocker = createRoomLocker(room);
  775. this._room = room; // FIXME do not use this
  776. let email = APP.settings.getEmail();
  777. email && sendEmail(this.commands.defaults.EMAIL, email);
  778. let nick = APP.settings.getDisplayName();
  779. if (config.useNicks && !nick) {
  780. nick = APP.UI.askForNickname();
  781. APP.settings.setDisplayName(nick);
  782. }
  783. nick && room.setDisplayName(nick);
  784. this._setupListeners();
  785. },
  786. _getConferenceOptions() {
  787. let options = config;
  788. if(config.enableRecording && !config.recordingType) {
  789. options.recordingType = (config.hosts &&
  790. (typeof config.hosts.jirecon != "undefined"))?
  791. "jirecon" : "colibri";
  792. }
  793. return options;
  794. },
  795. /**
  796. * Start using provided video stream.
  797. * Stops previous video stream.
  798. * @param {JitsiLocalTrack} [stream] new stream to use or null
  799. * @returns {Promise}
  800. */
  801. useVideoStream (stream) {
  802. let promise = Promise.resolve();
  803. if (localVideo) {
  804. // this calls room.removeTrack internally
  805. // so we don't need to remove it manually
  806. promise = localVideo.dispose();
  807. }
  808. localVideo = stream;
  809. return promise.then(function () {
  810. if (stream) {
  811. return room.addTrack(stream);
  812. }
  813. }).then(() => {
  814. if (stream) {
  815. this.videoMuted = stream.isMuted();
  816. this.isSharingScreen = stream.videoType === 'desktop';
  817. APP.UI.addLocalStream(stream);
  818. } else {
  819. this.videoMuted = false;
  820. this.isSharingScreen = false;
  821. }
  822. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  823. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  824. APP.UI.updateDesktopSharingButtons();
  825. });
  826. },
  827. /**
  828. * Start using provided audio stream.
  829. * Stops previous audio stream.
  830. * @param {JitsiLocalTrack} [stream] new stream to use or null
  831. * @returns {Promise}
  832. */
  833. useAudioStream (stream) {
  834. let promise = Promise.resolve();
  835. if (localAudio) {
  836. // this calls room.removeTrack internally
  837. // so we don't need to remove it manually
  838. promise = localAudio.dispose();
  839. }
  840. localAudio = stream;
  841. return promise.then(function () {
  842. if (stream) {
  843. return room.addTrack(stream);
  844. }
  845. }).then(() => {
  846. if (stream) {
  847. this.audioMuted = stream.isMuted();
  848. APP.UI.addLocalStream(stream);
  849. } else {
  850. this.audioMuted = false;
  851. }
  852. APP.UI.enableMicrophoneButton();
  853. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  854. });
  855. },
  856. videoSwitchInProgress: false,
  857. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  858. if (this.videoSwitchInProgress) {
  859. console.warn("Switch in progress.");
  860. return;
  861. }
  862. if (!this.isDesktopSharingEnabled) {
  863. console.warn("Cannot toggle screen sharing: not supported.");
  864. return;
  865. }
  866. this.videoSwitchInProgress = true;
  867. if (shareScreen) {
  868. createLocalTracks(['desktop']).then(([stream]) => {
  869. stream.on(
  870. TrackEvents.LOCAL_TRACK_STOPPED,
  871. () => {
  872. // if stream was stopped during screensharing session
  873. // then we should switch to video
  874. // otherwise we stopped it because we already switched
  875. // to video, so nothing to do here
  876. if (this.isSharingScreen) {
  877. this.toggleScreenSharing(false);
  878. }
  879. }
  880. );
  881. return this.useVideoStream(stream);
  882. }).then(() => {
  883. this.videoSwitchInProgress = false;
  884. console.log('sharing local desktop');
  885. }).catch((err) => {
  886. this.videoSwitchInProgress = false;
  887. this.toggleScreenSharing(false);
  888. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  889. return;
  890. console.error('failed to share local desktop', err);
  891. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  892. APP.UI.showExtensionRequiredDialog(
  893. config.desktopSharingFirefoxExtensionURL
  894. );
  895. return;
  896. }
  897. // Handling:
  898. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  899. // TrackErrors.GENERAL
  900. // and any other
  901. let dialogTxt = APP.translation
  902. .generateTranslationHTML("dialog.failtoinstall");
  903. let dialogTitle = APP.translation
  904. .generateTranslationHTML("dialog.error");
  905. APP.UI.messageHandler.openDialog(
  906. dialogTitle,
  907. dialogTxt,
  908. false
  909. );
  910. });
  911. } else {
  912. createLocalTracks(['video']).then(
  913. ([stream]) => this.useVideoStream(stream)
  914. ).then(() => {
  915. this.videoSwitchInProgress = false;
  916. console.log('sharing local video');
  917. }).catch((err) => {
  918. this.useVideoStream(null);
  919. this.videoSwitchInProgress = false;
  920. console.error('failed to share local video', err);
  921. });
  922. }
  923. },
  924. /**
  925. * Setup interaction between conference and UI.
  926. */
  927. _setupListeners () {
  928. // add local streams when joined to the conference
  929. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  930. APP.UI.mucJoined();
  931. });
  932. room.on(
  933. ConferenceEvents.AUTH_STATUS_CHANGED,
  934. function (authEnabled, authLogin) {
  935. APP.UI.updateAuthInfo(authEnabled, authLogin);
  936. }
  937. );
  938. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  939. if (user.isHidden())
  940. return;
  941. console.log('USER %s connnected', id, user);
  942. APP.API.notifyUserJoined(id);
  943. APP.UI.addUser(id, user.getDisplayName());
  944. // check the roles for the new user and reflect them
  945. APP.UI.updateUserRole(user);
  946. });
  947. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  948. console.log('USER %s LEFT', id, user);
  949. APP.API.notifyUserLeft(id);
  950. APP.UI.removeUser(id, user.getDisplayName());
  951. APP.UI.onSharedVideoStop(id);
  952. });
  953. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  954. if (this.isLocalId(id)) {
  955. console.info(`My role changed, new role: ${role}`);
  956. this.isModerator = room.isModerator();
  957. APP.UI.updateLocalRole(room.isModerator());
  958. } else {
  959. let user = room.getParticipantById(id);
  960. if (user) {
  961. APP.UI.updateUserRole(user);
  962. }
  963. }
  964. });
  965. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  966. if(!track || track.isLocal())
  967. return;
  968. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  969. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  970. });
  971. APP.UI.addRemoteStream(track);
  972. });
  973. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  974. if(!track || track.isLocal())
  975. return;
  976. APP.UI.removeRemoteStream(track);
  977. });
  978. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  979. if(!track)
  980. return;
  981. const handler = (track.getType() === "audio")?
  982. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  983. let id;
  984. const mute = track.isMuted();
  985. if(track.isLocal()){
  986. id = this.localId;
  987. if(track.getType() === "audio") {
  988. this.audioMuted = mute;
  989. } else {
  990. this.videoMuted = mute;
  991. }
  992. } else {
  993. id = track.getParticipantId();
  994. }
  995. handler(id , mute);
  996. });
  997. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  998. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  999. lvl = 0;
  1000. }
  1001. if(config.debug)
  1002. {
  1003. this.audioLevelsMap[id] = lvl;
  1004. console.log("AudioLevel:" + id + "/" + lvl);
  1005. }
  1006. APP.UI.setAudioLevel(id, lvl);
  1007. });
  1008. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1009. //FIXME
  1010. if (config.muteLocalVideoIfNotInLastN) {
  1011. // TODO mute or unmute if required
  1012. // mark video on UI
  1013. // APP.UI.markVideoMuted(true/false);
  1014. }
  1015. });
  1016. room.on(
  1017. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1018. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1019. });
  1020. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1021. APP.UI.markDominantSpeaker(id);
  1022. });
  1023. if (!interfaceConfig.filmStripOnly) {
  1024. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1025. APP.UI.markVideoInterrupted(true);
  1026. });
  1027. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1028. APP.UI.markVideoInterrupted(false);
  1029. });
  1030. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1031. let nick = getDisplayName(id);
  1032. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1033. APP.UI.addMessage(id, nick, text, ts);
  1034. });
  1035. }
  1036. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1037. APP.API.notifyDisplayNameChanged(id, displayName);
  1038. APP.UI.changeDisplayName(id, displayName);
  1039. });
  1040. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1041. console.log("Received recorder status change: ", status, error);
  1042. APP.UI.updateRecordingState(status);
  1043. });
  1044. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1045. APP.UI.updateUserStatus(id, status);
  1046. });
  1047. room.on(ConferenceEvents.KICKED, () => {
  1048. APP.UI.hideStats();
  1049. APP.UI.notifyKicked();
  1050. // FIXME close
  1051. });
  1052. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1053. APP.UI.updateDTMFSupport(isDTMFSupported);
  1054. });
  1055. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1056. if (room.isModerator()) {
  1057. let promise = roomLocker.isLocked
  1058. ? roomLocker.askToUnlock()
  1059. : roomLocker.askToLock();
  1060. promise.then(() => {
  1061. APP.UI.markRoomLocked(roomLocker.isLocked);
  1062. });
  1063. } else {
  1064. roomLocker.notifyModeratorRequired();
  1065. }
  1066. });
  1067. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1068. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1069. if (!interfaceConfig.filmStripOnly) {
  1070. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1071. APP.API.notifySendingChatMessage(message);
  1072. room.sendTextMessage(message);
  1073. });
  1074. }
  1075. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1076. ConnectionQuality.updateLocalStats(stats);
  1077. });
  1078. ConnectionQuality.addListener(
  1079. CQEvents.LOCALSTATS_UPDATED,
  1080. (percent, stats) => {
  1081. APP.UI.updateLocalStats(percent, stats);
  1082. // send local stats to other users
  1083. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  1084. {
  1085. children: ConnectionQuality.convertToMUCStats(stats),
  1086. attributes: {
  1087. xmlns: 'http://jitsi.org/jitmeet/stats'
  1088. }
  1089. });
  1090. }
  1091. );
  1092. // listen to remote stats
  1093. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  1094. (values, from) => {
  1095. ConnectionQuality.updateRemoteStats(from, values);
  1096. });
  1097. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1098. (id, percent, stats) => {
  1099. APP.UI.updateRemoteStats(id, percent, stats);
  1100. });
  1101. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1102. APP.UI.initEtherpad(value);
  1103. });
  1104. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  1105. email = email.trim();
  1106. if (email === APP.settings.getEmail()) {
  1107. return;
  1108. }
  1109. APP.settings.setEmail(email);
  1110. APP.UI.setUserAvatar(room.myUserId(), email);
  1111. sendEmail(this.commands.defaults.EMAIL, email);
  1112. });
  1113. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  1114. APP.UI.setUserAvatar(data.attributes.id, data.value);
  1115. });
  1116. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  1117. nickname = nickname.trim();
  1118. if (nickname === APP.settings.getDisplayName()) {
  1119. return;
  1120. }
  1121. APP.settings.setDisplayName(nickname);
  1122. room.setDisplayName(nickname);
  1123. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  1124. });
  1125. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1126. (startAudioMuted, startVideoMuted) => {
  1127. room.setStartMutedPolicy({
  1128. audio: startAudioMuted,
  1129. video: startVideoMuted
  1130. });
  1131. }
  1132. );
  1133. room.on(
  1134. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1135. ({ audio, video }) => {
  1136. APP.UI.onStartMutedChanged(audio, video);
  1137. }
  1138. );
  1139. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1140. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1141. && APP.UI.notifyInitiallyMuted();
  1142. });
  1143. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1144. APP.UI.inviteParticipants(
  1145. roomUrl,
  1146. APP.conference.roomName,
  1147. roomLocker.password,
  1148. APP.settings.getDisplayName()
  1149. );
  1150. });
  1151. room.on(
  1152. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1153. APP.UI.updateDevicesAvailability(id, devices);
  1154. }
  1155. );
  1156. // call hangup
  1157. APP.UI.addListener(UIEvents.HANGUP, () => {
  1158. hangup(true);
  1159. });
  1160. // logout
  1161. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1162. AuthHandler.logout(room).then(function (url) {
  1163. if (url) {
  1164. window.location.href = url;
  1165. } else {
  1166. hangup(true);
  1167. }
  1168. });
  1169. });
  1170. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1171. room.dial(sipNumber);
  1172. });
  1173. // Starts or stops the recording for the conference.
  1174. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1175. room.toggleRecording(options);
  1176. });
  1177. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1178. room.setSubject(topic);
  1179. });
  1180. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1181. APP.UI.setSubject(subject);
  1182. });
  1183. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1184. room.kickParticipant(id);
  1185. });
  1186. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1187. room.muteParticipant(id);
  1188. });
  1189. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1190. AuthHandler.authenticate(room);
  1191. });
  1192. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1193. room.selectParticipant(id);
  1194. });
  1195. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1196. var smallVideoId = smallVideo.getId();
  1197. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1198. && !APP.conference.isLocalId(smallVideoId))
  1199. if (isPinned)
  1200. room.pinParticipant(smallVideoId);
  1201. // When the library starts supporting multiple pins we would
  1202. // pass the isPinned parameter together with the identifier,
  1203. // but currently we send null to indicate that we unpin the
  1204. // last pinned.
  1205. else
  1206. room.pinParticipant(null);
  1207. });
  1208. APP.UI.addListener(
  1209. UIEvents.VIDEO_DEVICE_CHANGED,
  1210. (cameraDeviceId) => {
  1211. APP.settings.setCameraDeviceId(cameraDeviceId);
  1212. createLocalTracks(['video']).then(([stream]) => {
  1213. this.useVideoStream(stream);
  1214. console.log('switched local video device');
  1215. });
  1216. }
  1217. );
  1218. APP.UI.addListener(
  1219. UIEvents.AUDIO_DEVICE_CHANGED,
  1220. (micDeviceId) => {
  1221. APP.settings.setMicDeviceId(micDeviceId);
  1222. createLocalTracks(['audio']).then(([stream]) => {
  1223. this.useAudioStream(stream);
  1224. console.log('switched local audio device');
  1225. });
  1226. }
  1227. );
  1228. APP.UI.addListener(
  1229. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1230. (audioOutputDeviceId) => {
  1231. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1232. .then(() => console.log('changed audio output device'))
  1233. .catch((err) => {
  1234. console.error('failed to set audio output device', err);
  1235. });
  1236. }
  1237. );
  1238. APP.UI.addListener(
  1239. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1240. );
  1241. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1242. (url, state, time, isMuted, volume) => {
  1243. // send start and stop commands once, and remove any updates
  1244. // that had left
  1245. if (state === 'stop' || state === 'start' || state === 'playing') {
  1246. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1247. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1248. value: url,
  1249. attributes: {
  1250. state: state,
  1251. time: time,
  1252. muted: isMuted,
  1253. volume: volume
  1254. }
  1255. });
  1256. }
  1257. else {
  1258. // in case of paused, in order to allow late users to join
  1259. // paused
  1260. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1261. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1262. value: url,
  1263. attributes: {
  1264. state: state,
  1265. time: time,
  1266. muted: isMuted,
  1267. volume: volume
  1268. }
  1269. });
  1270. }
  1271. });
  1272. room.addCommandListener(
  1273. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1274. if (attributes.state === 'stop') {
  1275. APP.UI.onSharedVideoStop(id, attributes);
  1276. }
  1277. else if (attributes.state === 'start') {
  1278. APP.UI.onSharedVideoStart(id, value, attributes);
  1279. }
  1280. else if (attributes.state === 'playing'
  1281. || attributes.state === 'pause') {
  1282. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1283. }
  1284. });
  1285. },
  1286. /**
  1287. * Adss any room listener.
  1288. * @param eventName one of the ConferenceEvents
  1289. * @param callBack the function to be called when the event occurs
  1290. */
  1291. addConferenceListener(eventName, callBack) {
  1292. room.on(eventName, callBack);
  1293. }
  1294. };