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

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