您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 49KB

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