Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 63KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  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. import {reportError} from './modules/util/helpers';
  13. import UIErrors from './modules/UI/UIErrors';
  14. const ConnectionEvents = JitsiMeetJS.events.connection;
  15. const ConnectionErrors = JitsiMeetJS.errors.connection;
  16. const ConferenceEvents = JitsiMeetJS.events.conference;
  17. const ConferenceErrors = JitsiMeetJS.errors.conference;
  18. const TrackEvents = JitsiMeetJS.events.track;
  19. const TrackErrors = JitsiMeetJS.errors.track;
  20. let room, connection, localAudio, localVideo, roomLocker;
  21. /**
  22. * Indicates whether the connection is interrupted or not.
  23. */
  24. let connectionIsInterrupted = false;
  25. /**
  26. * Indicates whether extension external installation is in progress or not.
  27. */
  28. let DSExternalInstallationInProgress = false;
  29. /**
  30. * Listens whether conference had been left from local user when we are trying
  31. * to navigate away from current page.
  32. * @type {ConferenceLeftListener}
  33. */
  34. let conferenceLeftListener = null;
  35. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  36. /**
  37. * Known custom conference commands.
  38. */
  39. const commands = {
  40. CONNECTION_QUALITY: "stats",
  41. EMAIL: "email",
  42. AVATAR_URL: "avatar-url",
  43. AVATAR_ID: "avatar-id",
  44. ETHERPAD: "etherpad",
  45. SHARED_VIDEO: "shared-video",
  46. CUSTOM_ROLE: "custom-role"
  47. };
  48. /**
  49. * Open Connection. When authentication failed it shows auth dialog.
  50. * @param roomName the room name to use
  51. * @returns Promise<JitsiConnection>
  52. */
  53. function connect(roomName) {
  54. return openConnection({retry: true, roomName: roomName})
  55. .catch(function (err) {
  56. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  57. APP.UI.notifyTokenAuthFailed();
  58. } else {
  59. APP.UI.notifyConnectionFailed(err);
  60. }
  61. throw err;
  62. });
  63. }
  64. /**
  65. * Creates local media tracks and connects to room. Will show error
  66. * dialogs in case if accessing local microphone and/or camera failed. Will
  67. * show guidance overlay for users on how to give access to camera and/or
  68. * microphone,
  69. * @param {string} roomName
  70. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  71. */
  72. function createInitialLocalTracksAndConnect(roomName) {
  73. let audioAndVideoError,
  74. audioOnlyError;
  75. JitsiMeetJS.mediaDevices.addEventListener(
  76. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  77. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  78. // First try to retrieve both audio and video.
  79. let tryCreateLocalTracks = createLocalTracks(
  80. { devices: ['audio', 'video'] }, true)
  81. .catch(err => {
  82. // If failed then try to retrieve only audio.
  83. audioAndVideoError = err;
  84. return createLocalTracks({ devices: ['audio'] }, true);
  85. })
  86. .catch(err => {
  87. // If audio failed too then just return empty array for tracks.
  88. audioOnlyError = err;
  89. return [];
  90. });
  91. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  92. .then(([tracks, con]) => {
  93. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  94. if (audioAndVideoError) {
  95. if (audioOnlyError) {
  96. // If both requests for 'audio' + 'video' and 'audio' only
  97. // failed, we assume that there is some problems with user's
  98. // microphone and show corresponding dialog.
  99. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  100. } else {
  101. // If request for 'audio' + 'video' failed, but request for
  102. // 'audio' only was OK, we assume that we had problems with
  103. // camera and show corresponding dialog.
  104. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  105. }
  106. }
  107. return [tracks, con];
  108. });
  109. }
  110. /**
  111. * Share data to other users.
  112. * @param command the command
  113. * @param {string} value new value
  114. */
  115. function sendData (command, value) {
  116. room.removeCommand(command);
  117. room.sendCommand(command, {value: value});
  118. }
  119. /**
  120. * Get user nickname by user id.
  121. * @param {string} id user id
  122. * @returns {string?} user nickname or undefined if user is unknown.
  123. */
  124. function getDisplayName (id) {
  125. if (APP.conference.isLocalId(id)) {
  126. return APP.settings.getDisplayName();
  127. }
  128. let participant = room.getParticipantById(id);
  129. if (participant && participant.getDisplayName()) {
  130. return participant.getDisplayName();
  131. }
  132. }
  133. /**
  134. * Mute or unmute local audio stream if it exists.
  135. * @param {boolean} muted if audio stream should be muted or unmuted.
  136. * @param {boolean} indicates if this local audio mute was a result of user
  137. * interaction
  138. *
  139. */
  140. function muteLocalAudio (muted, userInteraction) {
  141. if (!localAudio) {
  142. return;
  143. }
  144. if (muted) {
  145. localAudio.mute().then(function(value) {},
  146. function(value) {
  147. console.warn('Audio Mute was rejected:', value);
  148. }
  149. );
  150. } else {
  151. localAudio.unmute().then(function(value) {},
  152. function(value) {
  153. console.warn('Audio unmute was rejected:', value);
  154. }
  155. );
  156. }
  157. }
  158. /**
  159. * Mute or unmute local video stream if it exists.
  160. * @param {boolean} muted if video stream should be muted or unmuted.
  161. */
  162. function muteLocalVideo (muted) {
  163. if (!localVideo) {
  164. return;
  165. }
  166. if (muted) {
  167. localVideo.mute().then(function(value) {},
  168. function(value) {
  169. console.warn('Video mute was rejected:', value);
  170. }
  171. );
  172. } else {
  173. localVideo.unmute().then(function(value) {},
  174. function(value) {
  175. console.warn('Video unmute was rejected:', value);
  176. }
  177. );
  178. }
  179. }
  180. /**
  181. * Check if the welcome page is enabled and redirects to it.
  182. * If requested show a thank you dialog before that.
  183. * If we have a close page enabled, redirect to it without
  184. * showing any other dialog.
  185. * @param {boolean} showThankYou whether we should show a thank you dialog
  186. */
  187. function maybeRedirectToWelcomePage(showThankYou) {
  188. // if close page is enabled redirect to it, without further action
  189. if (config.enableClosePage) {
  190. window.location.pathname = "close.html";
  191. return;
  192. }
  193. if (showThankYou) {
  194. APP.UI.messageHandler.openMessageDialog(
  195. null, null, null,
  196. APP.translation.translateString(
  197. "dialog.thankYou", {appName:interfaceConfig.APP_NAME}
  198. )
  199. );
  200. }
  201. if (!config.enableWelcomePage) {
  202. return;
  203. }
  204. // redirect to welcome page
  205. setTimeout(() => {
  206. APP.settings.setWelcomePageEnabled(true);
  207. window.location.pathname = "/";
  208. }, 3000);
  209. }
  210. /**
  211. * Executes connection.disconnect and shows the feedback dialog
  212. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  213. * @returns Promise.
  214. */
  215. function disconnectAndShowFeedback(requestFeedback) {
  216. APP.UI.hideRingOverLay();
  217. connection.disconnect();
  218. APP.API.notifyConferenceLeft(APP.conference.roomName);
  219. if (requestFeedback) {
  220. return APP.UI.requestFeedback();
  221. } else {
  222. return Promise.resolve();
  223. }
  224. }
  225. /**
  226. * Disconnect from the conference and optionally request user feedback.
  227. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  228. */
  229. function hangup (requestFeedback = false) {
  230. const errCallback = (err) => {
  231. // If we want to break out the chain in our error handler, it needs
  232. // to return a rejected promise. In the case of feedback request
  233. // in progress it's important to not redirect to the welcome page
  234. // (see below maybeRedirectToWelcomePage call).
  235. if (err === UIErrors.FEEDBACK_REQUEST_IN_PROGRESS) {
  236. return Promise.reject('Feedback request in progress.');
  237. }
  238. else {
  239. console.error('Error occurred during hanging up: ', err);
  240. return Promise.resolve();
  241. }
  242. };
  243. const disconnect = disconnectAndShowFeedback.bind(null, requestFeedback);
  244. if (!conferenceLeftListener)
  245. conferenceLeftListener = new ConferenceLeftListener();
  246. // Make sure that leave is resolved successfully and the set the handlers
  247. // to be invoked once conference had been left
  248. APP.conference._room.leave()
  249. .then(conferenceLeftListener.setHandler(disconnect, errCallback))
  250. .catch(errCallback);
  251. }
  252. /**
  253. * Listens for CONFERENCE_LEFT event so we can check whether it has finished.
  254. * The handler will be called once the conference had been left or if it
  255. * was already left when we are adding the handler.
  256. */
  257. class ConferenceLeftListener {
  258. /**
  259. * Creates ConferenceLeftListener and start listening for conference
  260. * failed event.
  261. */
  262. constructor() {
  263. room.on(ConferenceEvents.CONFERENCE_LEFT,
  264. this._handleConferenceLeft.bind(this));
  265. }
  266. /**
  267. * Handles the conference left event, if we have a handler we invoke it.
  268. * @private
  269. */
  270. _handleConferenceLeft() {
  271. this.conferenceLeft = true;
  272. if (this.handler)
  273. this._handleLeave();
  274. }
  275. /**
  276. * Sets the handlers. If we already left the conference invoke them.
  277. * @param handler
  278. * @param errCallback
  279. */
  280. setHandler (handler, errCallback) {
  281. this.handler = handler;
  282. this.errCallback = errCallback;
  283. if (this.conferenceLeft)
  284. this._handleLeave();
  285. }
  286. /**
  287. * Invokes the handlers.
  288. * @private
  289. */
  290. _handleLeave()
  291. {
  292. this.handler()
  293. .catch(this.errCallback)
  294. .then(maybeRedirectToWelcomePage)
  295. .catch(function(err){
  296. console.log(err);
  297. });
  298. }
  299. }
  300. /**
  301. * Create local tracks of specified types.
  302. * @param {Object} options
  303. * @param {string[]} options.devices - required track types
  304. * ('audio', 'video' etc.)
  305. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  306. * undefined - one from settings will be used
  307. * @param {string|null} (options.micDeviceId) - microphone device id, if
  308. * undefined - one from settings will be used
  309. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  310. * for gUM permission prompt
  311. * @returns {Promise<JitsiLocalTrack[]>}
  312. */
  313. function createLocalTracks (options, checkForPermissionPrompt) {
  314. options || (options = {});
  315. return JitsiMeetJS
  316. .createLocalTracks({
  317. // copy array to avoid mutations inside library
  318. devices: options.devices.slice(0),
  319. resolution: config.resolution,
  320. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  321. options.cameraDeviceId === null
  322. ? APP.settings.getCameraDeviceId()
  323. : options.cameraDeviceId,
  324. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  325. options.micDeviceId === null
  326. ? APP.settings.getMicDeviceId()
  327. : options.micDeviceId,
  328. // adds any ff fake device settings if any
  329. firefox_fake_device: config.firefox_fake_device,
  330. desktopSharingExtensionExternalInstallation:
  331. options.desktopSharingExtensionExternalInstallation
  332. }, checkForPermissionPrompt).then( (tracks) => {
  333. tracks.forEach((track) => {
  334. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  335. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  336. });
  337. return tracks;
  338. }).catch(function (err) {
  339. console.error(
  340. 'failed to create local tracks', options.devices, err);
  341. return Promise.reject(err);
  342. });
  343. }
  344. /**
  345. * Changes the email for the local user
  346. * @param email {string} the new email
  347. */
  348. function changeLocalEmail(email = '') {
  349. email = email.trim();
  350. if (email === APP.settings.getEmail()) {
  351. return;
  352. }
  353. APP.settings.setEmail(email);
  354. APP.UI.setUserEmail(room.myUserId(), email);
  355. sendData(commands.EMAIL, email);
  356. }
  357. /**
  358. * Changes the display name for the local user
  359. * @param nickname {string} the new display name
  360. */
  361. function changeLocalDisplayName(nickname = '') {
  362. nickname = nickname.trim();
  363. if (nickname === APP.settings.getDisplayName()) {
  364. return;
  365. }
  366. APP.settings.setDisplayName(nickname);
  367. room.setDisplayName(nickname);
  368. APP.UI.changeDisplayName(APP.conference.getMyUserId(), nickname);
  369. }
  370. class ConferenceConnector {
  371. constructor(resolve, reject) {
  372. this._resolve = resolve;
  373. this._reject = reject;
  374. this.reconnectTimeout = null;
  375. room.on(ConferenceEvents.CONFERENCE_JOINED,
  376. this._handleConferenceJoined.bind(this));
  377. room.on(ConferenceEvents.CONFERENCE_FAILED,
  378. this._onConferenceFailed.bind(this));
  379. room.on(ConferenceEvents.CONFERENCE_ERROR,
  380. this._onConferenceError.bind(this));
  381. }
  382. _handleConferenceFailed(err, msg) {
  383. this._unsubscribe();
  384. this._reject(err);
  385. }
  386. _onConferenceFailed(err, ...params) {
  387. console.error('CONFERENCE FAILED:', err, ...params);
  388. APP.UI.hideRingOverLay();
  389. switch (err) {
  390. // room is locked by the password
  391. case ConferenceErrors.PASSWORD_REQUIRED:
  392. APP.UI.markRoomLocked(true);
  393. roomLocker.requirePassword().then(function () {
  394. let pass = roomLocker.password;
  395. // we received that password is required, but user is trying
  396. // anyway to login without a password, mark room as not locked
  397. // in case he succeeds (maybe someone removed the password
  398. // meanwhile), if it is still locked another password required
  399. // will be received and the room again will be marked as locked
  400. if (!pass)
  401. APP.UI.markRoomLocked(false);
  402. room.join(roomLocker.password);
  403. });
  404. break;
  405. case ConferenceErrors.CONNECTION_ERROR:
  406. {
  407. let [msg] = params;
  408. APP.UI.notifyConnectionFailed(msg);
  409. }
  410. break;
  411. case ConferenceErrors.NOT_ALLOWED_ERROR:
  412. {
  413. // let's show some auth not allowed page
  414. window.location.pathname = "authError.html";
  415. }
  416. break;
  417. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  418. APP.UI.notifyBridgeDown();
  419. break;
  420. // not enough rights to create conference
  421. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  422. // schedule reconnect to check if someone else created the room
  423. this.reconnectTimeout = setTimeout(function () {
  424. room.join();
  425. }, 5000);
  426. // notify user that auth is required
  427. AuthHandler.requireAuth(room, roomLocker.password);
  428. break;
  429. case ConferenceErrors.RESERVATION_ERROR:
  430. {
  431. let [code, msg] = params;
  432. APP.UI.notifyReservationError(code, msg);
  433. }
  434. break;
  435. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  436. APP.UI.notifyGracefulShutdown();
  437. break;
  438. case ConferenceErrors.JINGLE_FATAL_ERROR:
  439. APP.UI.notifyInternalError();
  440. break;
  441. case ConferenceErrors.CONFERENCE_DESTROYED:
  442. {
  443. let [reason] = params;
  444. APP.UI.hideStats();
  445. APP.UI.notifyConferenceDestroyed(reason);
  446. }
  447. break;
  448. case ConferenceErrors.FOCUS_DISCONNECTED:
  449. {
  450. let [focus, retrySec] = params;
  451. APP.UI.notifyFocusDisconnected(focus, retrySec);
  452. }
  453. break;
  454. case ConferenceErrors.FOCUS_LEFT:
  455. room.leave().then(() => connection.disconnect());
  456. APP.UI.notifyFocusLeft();
  457. break;
  458. case ConferenceErrors.CONFERENCE_MAX_USERS:
  459. connection.disconnect();
  460. APP.UI.notifyMaxUsersLimitReached();
  461. break;
  462. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  463. window.location.reload();
  464. break;
  465. default:
  466. this._handleConferenceFailed(err, ...params);
  467. }
  468. }
  469. _onConferenceError(err, ...params) {
  470. console.error('CONFERENCE Error:', err, params);
  471. switch (err) {
  472. case ConferenceErrors.CHAT_ERROR:
  473. {
  474. let [code, msg] = params;
  475. APP.UI.showChatError(code, msg);
  476. }
  477. break;
  478. default:
  479. console.error("Unknown error.");
  480. }
  481. }
  482. _unsubscribe() {
  483. room.off(
  484. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  485. room.off(
  486. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  487. if (this.reconnectTimeout !== null) {
  488. clearTimeout(this.reconnectTimeout);
  489. }
  490. AuthHandler.closeAuth();
  491. }
  492. _handleConferenceJoined() {
  493. this._unsubscribe();
  494. this._resolve();
  495. }
  496. connect() {
  497. room.join();
  498. }
  499. }
  500. export default {
  501. isModerator: false,
  502. audioMuted: false,
  503. videoMuted: false,
  504. isSharingScreen: false,
  505. isDesktopSharingEnabled: false,
  506. /*
  507. * Whether the local "raisedHand" flag is on.
  508. */
  509. isHandRaised: false,
  510. /*
  511. * Whether the local participant is the dominant speaker in the conference.
  512. */
  513. isDominantSpeaker: false,
  514. /**
  515. * Open new connection and join to the conference.
  516. * @param {object} options
  517. * @param {string} roomName name of the conference
  518. * @returns {Promise}
  519. */
  520. init(options) {
  521. this.roomName = options.roomName;
  522. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  523. // attaches global error handler, if there is already one, respect it
  524. if(JitsiMeetJS.getGlobalOnErrorHandler){
  525. var oldOnErrorHandler = window.onerror;
  526. window.onerror = function (message, source, lineno, colno, error) {
  527. JitsiMeetJS.getGlobalOnErrorHandler(
  528. message, source, lineno, colno, error);
  529. if(oldOnErrorHandler)
  530. oldOnErrorHandler(message, source, lineno, colno, error);
  531. };
  532. var oldOnUnhandledRejection = window.onunhandledrejection;
  533. window.onunhandledrejection = function(event) {
  534. JitsiMeetJS.getGlobalOnErrorHandler(
  535. null, null, null, null, event.reason);
  536. if(oldOnUnhandledRejection)
  537. oldOnUnhandledRejection(event);
  538. };
  539. }
  540. return JitsiMeetJS.init(config)
  541. .then(() => createInitialLocalTracksAndConnect(options.roomName))
  542. .then(([tracks, con]) => {
  543. console.log('initialized with %s local tracks', tracks.length);
  544. APP.connection = connection = con;
  545. this._createRoom(tracks);
  546. this.isDesktopSharingEnabled =
  547. JitsiMeetJS.isDesktopSharingEnabled();
  548. // if user didn't give access to mic or camera or doesn't have
  549. // them at all, we disable corresponding toolbar buttons
  550. if (!tracks.find((t) => t.isAudioTrack())) {
  551. APP.UI.disableMicrophoneButton();
  552. }
  553. if (!tracks.find((t) => t.isVideoTrack())) {
  554. APP.UI.disableCameraButton();
  555. }
  556. this._initDeviceList();
  557. if (config.iAmRecorder)
  558. this.recorder = new Recorder();
  559. // XXX The API will take care of disconnecting from the XMPP
  560. // server (and, thus, leaving the room) on unload.
  561. return new Promise((resolve, reject) => {
  562. (new ConferenceConnector(resolve, reject)).connect();
  563. });
  564. });
  565. },
  566. /**
  567. * Check if id is id of the local user.
  568. * @param {string} id id to check
  569. * @returns {boolean}
  570. */
  571. isLocalId (id) {
  572. return this.getMyUserId() === id;
  573. },
  574. /**
  575. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  576. * @param mute true for mute and false for unmute.
  577. */
  578. muteAudio (mute) {
  579. muteLocalAudio(mute);
  580. },
  581. /**
  582. * Returns whether local audio is muted or not.
  583. * @returns {boolean}
  584. */
  585. isLocalAudioMuted() {
  586. return this.audioMuted;
  587. },
  588. /**
  589. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  590. */
  591. toggleAudioMuted () {
  592. this.muteAudio(!this.audioMuted);
  593. },
  594. /**
  595. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  596. * @param mute true for mute and false for unmute.
  597. */
  598. muteVideo (mute) {
  599. muteLocalVideo(mute);
  600. },
  601. /**
  602. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  603. */
  604. toggleVideoMuted () {
  605. this.muteVideo(!this.videoMuted);
  606. },
  607. /**
  608. * Retrieve list of conference participants (without local user).
  609. * @returns {JitsiParticipant[]}
  610. */
  611. listMembers () {
  612. return room.getParticipants();
  613. },
  614. /**
  615. * Retrieve list of ids of conference participants (without local user).
  616. * @returns {string[]}
  617. */
  618. listMembersIds () {
  619. return room.getParticipants().map(p => p.getId());
  620. },
  621. /**
  622. * Checks whether the participant identified by id is a moderator.
  623. * @id id to search for participant
  624. * @return {boolean} whether the participant is moderator
  625. */
  626. isParticipantModerator (id) {
  627. let user = room.getParticipantById(id);
  628. return user && user.isModerator();
  629. },
  630. /**
  631. * Check if SIP is supported.
  632. * @returns {boolean}
  633. */
  634. sipGatewayEnabled () {
  635. return room.isSIPCallingSupported();
  636. },
  637. get membersCount () {
  638. return room.getParticipants().length + 1;
  639. },
  640. /**
  641. * Returns true if the callstats integration is enabled, otherwise returns
  642. * false.
  643. *
  644. * @returns true if the callstats integration is enabled, otherwise returns
  645. * false.
  646. */
  647. isCallstatsEnabled () {
  648. return room.isCallstatsEnabled();
  649. },
  650. /**
  651. * Sends the given feedback through CallStats if enabled.
  652. *
  653. * @param overallFeedback an integer between 1 and 5 indicating the
  654. * user feedback
  655. * @param detailedFeedback detailed feedback from the user. Not yet used
  656. */
  657. sendFeedback (overallFeedback, detailedFeedback) {
  658. return room.sendFeedback (overallFeedback, detailedFeedback);
  659. },
  660. /**
  661. * Returns the connection times stored in the library.
  662. */
  663. getConnectionTimes () {
  664. return this._room.getConnectionTimes();
  665. },
  666. // used by torture currently
  667. isJoined () {
  668. return this._room
  669. && this._room.isJoined();
  670. },
  671. getConnectionState () {
  672. return this._room
  673. && this._room.getConnectionState();
  674. },
  675. /**
  676. * Checks whether or not our connection is currently in interrupted and
  677. * reconnect attempts are in progress.
  678. *
  679. * @returns {boolean} true if the connection is in interrupted state or
  680. * false otherwise.
  681. */
  682. isConnectionInterrupted () {
  683. return connectionIsInterrupted;
  684. },
  685. /**
  686. * Finds JitsiParticipant for given id.
  687. *
  688. * @param {string} id participant's identifier(MUC nickname).
  689. *
  690. * @returns {JitsiParticipant|null} participant instance for given id or
  691. * null if not found.
  692. */
  693. getParticipantById (id) {
  694. return room ? room.getParticipantById(id) : null;
  695. },
  696. /**
  697. * Checks whether the user identified by given id is currently connected.
  698. *
  699. * @param {string} id participant's identifier(MUC nickname)
  700. *
  701. * @returns {boolean|null} true if participant's connection is ok or false
  702. * if the user is having connectivity issues.
  703. */
  704. isParticipantConnectionActive (id) {
  705. let participant = this.getParticipantById(id);
  706. return participant ? participant.isConnectionActive() : null;
  707. },
  708. /**
  709. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  710. * the given <tt>id</tt>.
  711. *
  712. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  713. *
  714. * @return {string} the participant's display name or the default string if
  715. * absent.
  716. */
  717. getParticipantDisplayName (id) {
  718. let displayName = getDisplayName(id);
  719. if (displayName) {
  720. return displayName;
  721. } else {
  722. if (APP.conference.isLocalId(id)) {
  723. return APP.translation.generateTranslationHTML(
  724. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  725. } else {
  726. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  727. }
  728. }
  729. },
  730. getMyUserId () {
  731. return this._room
  732. && this._room.myUserId();
  733. },
  734. /**
  735. * Indicates if recording is supported in this conference.
  736. */
  737. isRecordingSupported() {
  738. return this._room && this._room.isRecordingSupported();
  739. },
  740. /**
  741. * Returns the recording state or undefined if the room is not defined.
  742. */
  743. getRecordingState() {
  744. return (this._room) ? this._room.getRecordingState() : undefined;
  745. },
  746. /**
  747. * Will be filled with values only when config.debug is enabled.
  748. * Its used by torture to check audio levels.
  749. */
  750. audioLevelsMap: {},
  751. /**
  752. * Returns the stored audio level (stored only if config.debug is enabled)
  753. * @param id the id for the user audio level to return (the id value is
  754. * returned for the participant using getMyUserId() method)
  755. */
  756. getPeerSSRCAudioLevel (id) {
  757. return this.audioLevelsMap[id];
  758. },
  759. /**
  760. * @return {number} the number of participants in the conference with at
  761. * least one track.
  762. */
  763. getNumberOfParticipantsWithTracks() {
  764. return this._room.getParticipants()
  765. .filter((p) => p.getTracks().length > 0)
  766. .length;
  767. },
  768. /**
  769. * Returns the stats.
  770. */
  771. getStats() {
  772. return ConnectionQuality.getStats();
  773. },
  774. // end used by torture
  775. getLogs () {
  776. return room.getLogs();
  777. },
  778. /**
  779. * Download logs, a function that can be called from console while
  780. * debugging.
  781. * @param filename (optional) specify target filename
  782. */
  783. saveLogs (filename = 'meetlog.json') {
  784. // this can be called from console and will not have reference to this
  785. // that's why we reference the global var
  786. let logs = APP.conference.getLogs();
  787. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  788. let elem = document.createElement('a');
  789. elem.download = filename;
  790. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  791. elem.dataset.downloadurl
  792. = ['text/json', elem.download, elem.href].join(':');
  793. elem.dispatchEvent(new MouseEvent('click', {
  794. view: window,
  795. bubbles: true,
  796. cancelable: false
  797. }));
  798. },
  799. /**
  800. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  801. * desire to keep room private to this instance and (2) the need of other
  802. * modules to send and receive commands to and from participants.
  803. * Eventually, this instance remains in control with respect to the
  804. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  805. * JitsiConference) is to be used in the implementation of the Command(s)
  806. * API of this instance.
  807. */
  808. commands: {
  809. /**
  810. * Known custom conference commands.
  811. */
  812. defaults: commands,
  813. /**
  814. * Receives notifications from other participants about commands aka
  815. * custom events (sent by sendCommand or sendCommandOnce methods).
  816. * @param command {String} the name of the command
  817. * @param handler {Function} handler for the command
  818. */
  819. addCommandListener () {
  820. room.addCommandListener.apply(room, arguments);
  821. },
  822. /**
  823. * Removes command.
  824. * @param name {String} the name of the command.
  825. */
  826. removeCommand () {
  827. room.removeCommand.apply(room, arguments);
  828. },
  829. /**
  830. * Sends command.
  831. * @param name {String} the name of the command.
  832. * @param values {Object} with keys and values that will be sent.
  833. */
  834. sendCommand () {
  835. room.sendCommand.apply(room, arguments);
  836. },
  837. /**
  838. * Sends command one time.
  839. * @param name {String} the name of the command.
  840. * @param values {Object} with keys and values that will be sent.
  841. */
  842. sendCommandOnce () {
  843. room.sendCommandOnce.apply(room, arguments);
  844. }
  845. },
  846. _createRoom (localTracks) {
  847. room = connection.initJitsiConference(APP.conference.roomName,
  848. this._getConferenceOptions());
  849. this._setLocalAudioVideoStreams(localTracks);
  850. roomLocker = createRoomLocker(room);
  851. this._room = room; // FIXME do not use this
  852. let email = APP.settings.getEmail();
  853. email && sendData(this.commands.defaults.EMAIL, email);
  854. let avatarUrl = APP.settings.getAvatarUrl();
  855. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  856. avatarUrl);
  857. !email && sendData(
  858. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  859. let nick = APP.settings.getDisplayName();
  860. if (config.useNicks && !nick) {
  861. nick = APP.UI.askForNickname();
  862. APP.settings.setDisplayName(nick);
  863. }
  864. nick && room.setDisplayName(nick);
  865. this._setupListeners();
  866. },
  867. /**
  868. * Sets local video and audio streams.
  869. * @param {JitsiLocalTrack[]} tracks=[]
  870. * @returns {Promise[]}
  871. * @private
  872. */
  873. _setLocalAudioVideoStreams(tracks = []) {
  874. return tracks.map(track => {
  875. if (track.isAudioTrack()) {
  876. return this.useAudioStream(track);
  877. } else if (track.isVideoTrack()) {
  878. return this.useVideoStream(track);
  879. } else {
  880. console.error(
  881. "Ignored not an audio nor a video track: ", track);
  882. return Promise.resolve();
  883. }
  884. });
  885. },
  886. _getConferenceOptions() {
  887. let options = config;
  888. if(config.enableRecording && !config.recordingType) {
  889. options.recordingType = (config.hosts &&
  890. (typeof config.hosts.jirecon != "undefined"))?
  891. "jirecon" : "colibri";
  892. }
  893. return options;
  894. },
  895. /**
  896. * Start using provided video stream.
  897. * Stops previous video stream.
  898. * @param {JitsiLocalTrack} [stream] new stream to use or null
  899. * @returns {Promise}
  900. */
  901. useVideoStream (stream) {
  902. let promise = Promise.resolve();
  903. if (localVideo) {
  904. // this calls room.removeTrack internally
  905. // so we don't need to remove it manually
  906. promise = localVideo.dispose();
  907. }
  908. localVideo = stream;
  909. return promise.then(function () {
  910. if (stream) {
  911. return room.addTrack(stream);
  912. }
  913. }).then(() => {
  914. if (stream) {
  915. this.videoMuted = stream.isMuted();
  916. this.isSharingScreen = stream.videoType === 'desktop';
  917. APP.UI.addLocalStream(stream);
  918. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  919. } else {
  920. this.videoMuted = false;
  921. this.isSharingScreen = false;
  922. }
  923. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  924. APP.UI.updateDesktopSharingButtons();
  925. });
  926. },
  927. /**
  928. * Start using provided audio stream.
  929. * Stops previous audio stream.
  930. * @param {JitsiLocalTrack} [stream] new stream to use or null
  931. * @returns {Promise}
  932. */
  933. useAudioStream (stream) {
  934. let promise = Promise.resolve();
  935. if (localAudio) {
  936. // this calls room.removeTrack internally
  937. // so we don't need to remove it manually
  938. promise = localAudio.dispose();
  939. }
  940. localAudio = stream;
  941. return promise.then(function () {
  942. if (stream) {
  943. return room.addTrack(stream);
  944. }
  945. }).then(() => {
  946. if (stream) {
  947. this.audioMuted = stream.isMuted();
  948. APP.UI.addLocalStream(stream);
  949. } else {
  950. this.audioMuted = false;
  951. }
  952. APP.UI.enableMicrophoneButton();
  953. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  954. });
  955. },
  956. videoSwitchInProgress: false,
  957. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  958. if (this.videoSwitchInProgress) {
  959. console.warn("Switch in progress.");
  960. return;
  961. }
  962. if (!this.isDesktopSharingEnabled) {
  963. console.warn("Cannot toggle screen sharing: not supported.");
  964. return;
  965. }
  966. this.videoSwitchInProgress = true;
  967. let externalInstallation = false;
  968. if (shareScreen) {
  969. createLocalTracks({
  970. devices: ['desktop'],
  971. desktopSharingExtensionExternalInstallation: {
  972. interval: 500,
  973. checkAgain: () => {
  974. return DSExternalInstallationInProgress;
  975. },
  976. listener: (status, url) => {
  977. switch(status) {
  978. case "waitingForExtension":
  979. DSExternalInstallationInProgress = true;
  980. externalInstallation = true;
  981. APP.UI.showExtensionExternalInstallationDialog(
  982. url);
  983. break;
  984. case "extensionFound":
  985. if(externalInstallation) //close the dialog
  986. $.prompt.close();
  987. break;
  988. default:
  989. //Unknown status
  990. }
  991. }
  992. }
  993. }).then(([stream]) => {
  994. DSExternalInstallationInProgress = false;
  995. // close external installation dialog on success.
  996. if(externalInstallation)
  997. $.prompt.close();
  998. stream.on(
  999. TrackEvents.LOCAL_TRACK_STOPPED,
  1000. () => {
  1001. // if stream was stopped during screensharing session
  1002. // then we should switch to video
  1003. // otherwise we stopped it because we already switched
  1004. // to video, so nothing to do here
  1005. if (this.isSharingScreen) {
  1006. this.toggleScreenSharing(false);
  1007. }
  1008. }
  1009. );
  1010. return this.useVideoStream(stream);
  1011. }).then(() => {
  1012. this.videoSwitchInProgress = false;
  1013. JitsiMeetJS.analytics.sendEvent(
  1014. 'conference.sharingDesktop.start');
  1015. console.log('sharing local desktop');
  1016. }).catch((err) => {
  1017. // close external installation dialog to show the error.
  1018. if(externalInstallation)
  1019. $.prompt.close();
  1020. this.videoSwitchInProgress = false;
  1021. this.toggleScreenSharing(false);
  1022. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1023. return;
  1024. }
  1025. console.error('failed to share local desktop', err);
  1026. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1027. APP.UI.showExtensionRequiredDialog(
  1028. config.desktopSharingFirefoxExtensionURL
  1029. );
  1030. return;
  1031. }
  1032. // Handling:
  1033. // TrackErrors.PERMISSION_DENIED
  1034. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1035. // TrackErrors.GENERAL
  1036. // and any other
  1037. let dialogTxt;
  1038. let dialogTitle;
  1039. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1040. dialogTxt = APP.translation.generateTranslationHTML(
  1041. "dialog.screenSharingPermissionDeniedError");
  1042. dialogTitle = APP.translation.generateTranslationHTML(
  1043. "dialog.error");
  1044. } else {
  1045. dialogTxt = APP.translation.generateTranslationHTML(
  1046. "dialog.failtoinstall");
  1047. dialogTitle = APP.translation.generateTranslationHTML(
  1048. "dialog.permissionDenied");
  1049. }
  1050. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  1051. });
  1052. } else {
  1053. createLocalTracks({ devices: ['video'] }).then(
  1054. ([stream]) => this.useVideoStream(stream)
  1055. ).then(() => {
  1056. this.videoSwitchInProgress = false;
  1057. JitsiMeetJS.analytics.sendEvent(
  1058. 'conference.sharingDesktop.stop');
  1059. console.log('sharing local video');
  1060. }).catch((err) => {
  1061. this.useVideoStream(null);
  1062. this.videoSwitchInProgress = false;
  1063. console.error('failed to share local video', err);
  1064. });
  1065. }
  1066. },
  1067. /**
  1068. * Setup interaction between conference and UI.
  1069. */
  1070. _setupListeners () {
  1071. // add local streams when joined to the conference
  1072. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1073. APP.UI.mucJoined();
  1074. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1075. connectionIsInterrupted = false;
  1076. APP.UI.markVideoInterrupted(false);
  1077. });
  1078. room.on(
  1079. ConferenceEvents.AUTH_STATUS_CHANGED,
  1080. function (authEnabled, authLogin) {
  1081. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1082. }
  1083. );
  1084. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1085. if (user.isHidden())
  1086. return;
  1087. console.log('USER %s connnected', id, user);
  1088. APP.API.notifyUserJoined(id);
  1089. APP.UI.addUser(user);
  1090. // check the roles for the new user and reflect them
  1091. APP.UI.updateUserRole(user);
  1092. });
  1093. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1094. console.log('USER %s LEFT', id, user);
  1095. APP.API.notifyUserLeft(id);
  1096. APP.UI.removeUser(id, user.getDisplayName());
  1097. APP.UI.onSharedVideoStop(id);
  1098. });
  1099. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1100. if (this.isLocalId(id)) {
  1101. console.info(`My role changed, new role: ${role}`);
  1102. if (this.isModerator !== room.isModerator()) {
  1103. this.isModerator = room.isModerator();
  1104. APP.UI.updateLocalRole(room.isModerator());
  1105. }
  1106. } else {
  1107. let user = room.getParticipantById(id);
  1108. if (user) {
  1109. APP.UI.updateUserRole(user);
  1110. }
  1111. }
  1112. });
  1113. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1114. if(!track || track.isLocal())
  1115. return;
  1116. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1117. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1118. });
  1119. APP.UI.addRemoteStream(track);
  1120. });
  1121. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1122. if(!track || track.isLocal())
  1123. return;
  1124. APP.UI.removeRemoteStream(track);
  1125. });
  1126. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1127. if(!track)
  1128. return;
  1129. const handler = (track.getType() === "audio")?
  1130. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1131. let id;
  1132. const mute = track.isMuted();
  1133. if(track.isLocal()){
  1134. id = APP.conference.getMyUserId();
  1135. if(track.getType() === "audio") {
  1136. this.audioMuted = mute;
  1137. } else {
  1138. this.videoMuted = mute;
  1139. }
  1140. } else {
  1141. id = track.getParticipantId();
  1142. }
  1143. handler(id , mute);
  1144. });
  1145. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1146. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1147. lvl = 0;
  1148. }
  1149. if(config.debug)
  1150. {
  1151. this.audioLevelsMap[id] = lvl;
  1152. if(config.debugAudioLevels)
  1153. console.log("AudioLevel:" + id + "/" + lvl);
  1154. }
  1155. APP.UI.setAudioLevel(id, lvl);
  1156. });
  1157. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1158. //FIXME
  1159. if (config.muteLocalVideoIfNotInLastN) {
  1160. // TODO mute or unmute if required
  1161. // mark video on UI
  1162. // APP.UI.markVideoMuted(true/false);
  1163. }
  1164. });
  1165. room.on(
  1166. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1167. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1168. });
  1169. room.on(
  1170. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1171. (id, isActive) => {
  1172. APP.UI.participantConnectionStatusChanged(id, isActive);
  1173. });
  1174. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1175. if (this.isLocalId(id)) {
  1176. this.isDominantSpeaker = true;
  1177. this.setRaisedHand(false);
  1178. } else {
  1179. this.isDominantSpeaker = false;
  1180. var participant = room.getParticipantById(id);
  1181. if (participant) {
  1182. APP.UI.setRaisedHandStatus(participant, false);
  1183. }
  1184. }
  1185. APP.UI.markDominantSpeaker(id);
  1186. });
  1187. if (!interfaceConfig.filmStripOnly) {
  1188. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1189. APP.UI.markVideoInterrupted(true);
  1190. });
  1191. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1192. APP.UI.markVideoInterrupted(false);
  1193. });
  1194. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1195. let nick = getDisplayName(id);
  1196. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1197. APP.UI.addMessage(id, nick, text, ts);
  1198. });
  1199. }
  1200. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1201. connectionIsInterrupted = true;
  1202. ConnectionQuality.updateLocalConnectionQuality(0);
  1203. APP.UI.showLocalConnectionInterrupted(true);
  1204. });
  1205. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1206. connectionIsInterrupted = false;
  1207. APP.UI.showLocalConnectionInterrupted(false);
  1208. });
  1209. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1210. APP.API.notifyDisplayNameChanged(id, displayName);
  1211. APP.UI.changeDisplayName(id, displayName);
  1212. });
  1213. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1214. (participant, name, oldValue, newValue) => {
  1215. if (name === "raisedHand") {
  1216. APP.UI.setRaisedHandStatus(participant, newValue);
  1217. }
  1218. });
  1219. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1220. console.log("Received recorder status change: ", status, error);
  1221. APP.UI.updateRecordingState(status);
  1222. });
  1223. room.on(ConferenceEvents.LOCK_STATE_CHANGED, (state, error) => {
  1224. console.log("Received channel password lock change: ", state,
  1225. error);
  1226. APP.UI.markRoomLocked(state);
  1227. roomLocker.lockedElsewhere = state;
  1228. });
  1229. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1230. APP.UI.updateUserStatus(id, status);
  1231. });
  1232. room.on(ConferenceEvents.KICKED, () => {
  1233. APP.UI.hideStats();
  1234. APP.UI.notifyKicked();
  1235. // FIXME close
  1236. });
  1237. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1238. APP.UI.updateDTMFSupport(isDTMFSupported);
  1239. });
  1240. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1241. // Wait a little bit more just to be sure that we won't miss the
  1242. // extension installation
  1243. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1244. });
  1245. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1246. window.open(
  1247. url, "extension_store_window",
  1248. "resizable,scrollbars=yes,status=1");
  1249. });
  1250. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1251. if (room.isModerator()) {
  1252. let promise = roomLocker.isLocked
  1253. ? roomLocker.askToUnlock()
  1254. : roomLocker.askToLock();
  1255. promise.then(() => {
  1256. APP.UI.markRoomLocked(roomLocker.isLocked);
  1257. });
  1258. } else {
  1259. roomLocker.notifyModeratorRequired();
  1260. }
  1261. });
  1262. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1263. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1264. if (!interfaceConfig.filmStripOnly) {
  1265. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1266. APP.API.notifySendingChatMessage(message);
  1267. room.sendTextMessage(message);
  1268. });
  1269. }
  1270. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1271. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1272. });
  1273. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1274. (percent, stats) => {
  1275. APP.UI.updateLocalStats(percent, stats);
  1276. // Send only the data that remote participants care about.
  1277. let data = {
  1278. bitrate: stats.bitrate,
  1279. packetLoss: stats.packetLoss};
  1280. try {
  1281. room.broadcastEndpointMessage({
  1282. type: this.commands.defaults.CONNECTION_QUALITY,
  1283. values: data });
  1284. } catch (e) {
  1285. reportError(e);
  1286. }
  1287. });
  1288. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1289. (participant, payload) => {
  1290. switch(payload.type) {
  1291. case this.commands.defaults.CONNECTION_QUALITY:
  1292. ConnectionQuality.updateRemoteStats(participant.getId(),
  1293. payload.values);
  1294. break;
  1295. default:
  1296. console.warn("Unknown datachannel message", payload);
  1297. }
  1298. });
  1299. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1300. (id, percent, stats) => {
  1301. APP.UI.updateRemoteStats(id, percent, stats);
  1302. });
  1303. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1304. APP.UI.initEtherpad(value);
  1305. });
  1306. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1307. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1308. APP.UI.setUserEmail(from, data.value);
  1309. });
  1310. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1311. (data, from) => {
  1312. APP.UI.setUserAvatarUrl(from, data.value);
  1313. });
  1314. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1315. (data, from) => {
  1316. APP.UI.setUserAvatarID(from, data.value);
  1317. });
  1318. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1319. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1320. (startAudioMuted, startVideoMuted) => {
  1321. room.setStartMutedPolicy({
  1322. audio: startAudioMuted,
  1323. video: startVideoMuted
  1324. });
  1325. }
  1326. );
  1327. room.on(
  1328. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1329. ({ audio, video }) => {
  1330. APP.UI.onStartMutedChanged(audio, video);
  1331. }
  1332. );
  1333. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1334. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1335. && APP.UI.notifyInitiallyMuted();
  1336. });
  1337. room.on(
  1338. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1339. APP.UI.updateDevicesAvailability(id, devices);
  1340. }
  1341. );
  1342. // call hangup
  1343. APP.UI.addListener(UIEvents.HANGUP, () => {
  1344. hangup(true);
  1345. });
  1346. // logout
  1347. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1348. AuthHandler.logout(room).then(function (url) {
  1349. if (url) {
  1350. window.location.href = url;
  1351. } else {
  1352. hangup(true);
  1353. }
  1354. });
  1355. });
  1356. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1357. room.dial(sipNumber);
  1358. });
  1359. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1360. (id, oldResolution, newResolution, delay) => {
  1361. var logObject = {
  1362. id: "resolution_change",
  1363. participant: id,
  1364. oldValue: oldResolution,
  1365. newValue: newResolution,
  1366. delay: delay
  1367. };
  1368. room.sendApplicationLog(JSON.stringify(logObject));
  1369. // We only care about the delay between simulcast streams.
  1370. // Longer delays will be caused by something else and will just
  1371. // poison the data.
  1372. if (delay < 2000) {
  1373. JitsiMeetJS.analytics.sendEvent('stream.switch.delay', delay);
  1374. }
  1375. });
  1376. // Starts or stops the recording for the conference.
  1377. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1378. room.toggleRecording(options);
  1379. });
  1380. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1381. room.setSubject(topic);
  1382. });
  1383. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1384. APP.UI.setSubject(subject);
  1385. });
  1386. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1387. room.kickParticipant(id);
  1388. });
  1389. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1390. room.muteParticipant(id);
  1391. });
  1392. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1393. AuthHandler.authenticate(room);
  1394. });
  1395. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1396. try {
  1397. // do not try to select participant if there is none (we are
  1398. // alone in the room), otherwise an error will be thrown cause
  1399. // reporting mechanism is not available (datachannels currently)
  1400. if (room.getParticipants().length === 0)
  1401. return;
  1402. room.selectParticipant(id);
  1403. } catch (e) {
  1404. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1405. reportError(e);
  1406. }
  1407. });
  1408. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1409. var smallVideoId = smallVideo.getId();
  1410. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1411. // the participant is on the large video ?
  1412. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1413. && !APP.conference.isLocalId(smallVideoId)) {
  1414. // When the library starts supporting multiple pins we would
  1415. // pass the isPinned parameter together with the identifier,
  1416. // but currently we send null to indicate that we unpin the
  1417. // last pinned.
  1418. try {
  1419. room.pinParticipant(isPinned ? smallVideoId : null);
  1420. } catch (e) {
  1421. reportError(e);
  1422. }
  1423. }
  1424. });
  1425. APP.UI.addListener(
  1426. UIEvents.VIDEO_DEVICE_CHANGED,
  1427. (cameraDeviceId) => {
  1428. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1429. createLocalTracks({
  1430. devices: ['video'],
  1431. cameraDeviceId: cameraDeviceId,
  1432. micDeviceId: null
  1433. })
  1434. .then(([stream]) => {
  1435. this.useVideoStream(stream);
  1436. console.log('switched local video device');
  1437. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1438. })
  1439. .catch((err) => {
  1440. APP.UI.showDeviceErrorDialog(null, err);
  1441. APP.UI.setSelectedCameraFromSettings();
  1442. });
  1443. }
  1444. );
  1445. APP.UI.addListener(
  1446. UIEvents.AUDIO_DEVICE_CHANGED,
  1447. (micDeviceId) => {
  1448. JitsiMeetJS.analytics.sendEvent(
  1449. 'settings.changeDevice.audioIn');
  1450. createLocalTracks({
  1451. devices: ['audio'],
  1452. cameraDeviceId: null,
  1453. micDeviceId: micDeviceId
  1454. })
  1455. .then(([stream]) => {
  1456. this.useAudioStream(stream);
  1457. console.log('switched local audio device');
  1458. APP.settings.setMicDeviceId(micDeviceId, true);
  1459. })
  1460. .catch((err) => {
  1461. APP.UI.showDeviceErrorDialog(err, null);
  1462. APP.UI.setSelectedMicFromSettings();
  1463. });
  1464. }
  1465. );
  1466. APP.UI.addListener(
  1467. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1468. (audioOutputDeviceId) => {
  1469. JitsiMeetJS.analytics.sendEvent(
  1470. 'settings.changeDevice.audioOut');
  1471. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1472. .then(() => console.log('changed audio output device'))
  1473. .catch((err) => {
  1474. console.warn('Failed to change audio output device. ' +
  1475. 'Default or previously set audio output device ' +
  1476. 'will be used instead.', err);
  1477. APP.UI.setSelectedAudioOutputFromSettings();
  1478. });
  1479. }
  1480. );
  1481. APP.UI.addListener(
  1482. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1483. );
  1484. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1485. (url, state, time, isMuted, volume) => {
  1486. // send start and stop commands once, and remove any updates
  1487. // that had left
  1488. if (state === 'stop' || state === 'start' || state === 'playing') {
  1489. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1490. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1491. value: url,
  1492. attributes: {
  1493. state: state,
  1494. time: time,
  1495. muted: isMuted,
  1496. volume: volume
  1497. }
  1498. });
  1499. }
  1500. else {
  1501. // in case of paused, in order to allow late users to join
  1502. // paused
  1503. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1504. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1505. value: url,
  1506. attributes: {
  1507. state: state,
  1508. time: time,
  1509. muted: isMuted,
  1510. volume: volume
  1511. }
  1512. });
  1513. }
  1514. });
  1515. room.addCommandListener(
  1516. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1517. if (attributes.state === 'stop') {
  1518. APP.UI.onSharedVideoStop(id, attributes);
  1519. }
  1520. else if (attributes.state === 'start') {
  1521. APP.UI.onSharedVideoStart(id, value, attributes);
  1522. }
  1523. else if (attributes.state === 'playing'
  1524. || attributes.state === 'pause') {
  1525. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1526. }
  1527. });
  1528. },
  1529. /**
  1530. * Adds any room listener.
  1531. * @param eventName one of the ConferenceEvents
  1532. * @param callBack the function to be called when the event occurs
  1533. */
  1534. addConferenceListener(eventName, callBack) {
  1535. room.on(eventName, callBack);
  1536. },
  1537. /**
  1538. * Inits list of current devices and event listener for device change.
  1539. * @private
  1540. */
  1541. _initDeviceList() {
  1542. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1543. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1544. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1545. // Ugly way to synchronize real device IDs with local
  1546. // storage and settings menu. This is a workaround until
  1547. // getConstraints() method will be implemented in browsers.
  1548. if (localAudio) {
  1549. APP.settings.setMicDeviceId(
  1550. localAudio.getDeviceId(), false);
  1551. }
  1552. if (localVideo) {
  1553. APP.settings.setCameraDeviceId(
  1554. localVideo.getDeviceId(), false);
  1555. }
  1556. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1557. APP.UI.onAvailableDevicesChanged(devices);
  1558. });
  1559. JitsiMeetJS.mediaDevices.addEventListener(
  1560. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1561. (devices) =>
  1562. window.setTimeout(
  1563. () => this._onDeviceListChanged(devices), 0));
  1564. }
  1565. },
  1566. /**
  1567. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1568. * handle change of available media devices.
  1569. * @private
  1570. * @param {MediaDeviceInfo[]} devices
  1571. * @returns {Promise}
  1572. */
  1573. _onDeviceListChanged(devices) {
  1574. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1575. // Event handler can be fired before direct
  1576. // enumerateDevices() call, so handle this situation here.
  1577. if (!currentDevices.audioinput &&
  1578. !currentDevices.videoinput &&
  1579. !currentDevices.audiooutput) {
  1580. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1581. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1582. }
  1583. let newDevices =
  1584. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1585. devices, this.isSharingScreen, localVideo, localAudio);
  1586. let promises = [];
  1587. let audioWasMuted = this.audioMuted;
  1588. let videoWasMuted = this.videoMuted;
  1589. let availableAudioInputDevices =
  1590. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1591. let availableVideoInputDevices =
  1592. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1593. if (typeof newDevices.audiooutput !== 'undefined') {
  1594. // Just ignore any errors in catch block.
  1595. promises.push(APP.settings
  1596. .setAudioOutputDeviceId(newDevices.audiooutput)
  1597. .catch());
  1598. }
  1599. promises.push(
  1600. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1601. createLocalTracks,
  1602. newDevices.videoinput,
  1603. newDevices.audioinput)
  1604. .then(tracks =>
  1605. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1606. .then(() => {
  1607. // If audio was muted before, or we unplugged current device
  1608. // and selected new one, then mute new audio track.
  1609. if (audioWasMuted ||
  1610. currentDevices.audioinput.length >
  1611. availableAudioInputDevices.length) {
  1612. muteLocalAudio(true);
  1613. }
  1614. // If video was muted before, or we unplugged current device
  1615. // and selected new one, then mute new video track.
  1616. if (videoWasMuted ||
  1617. currentDevices.videoinput.length >
  1618. availableVideoInputDevices.length) {
  1619. muteLocalVideo(true);
  1620. }
  1621. }));
  1622. return Promise.all(promises)
  1623. .then(() => {
  1624. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1625. APP.UI.onAvailableDevicesChanged(devices);
  1626. });
  1627. },
  1628. /**
  1629. * Toggles the local "raised hand" status, if the current state allows
  1630. * toggling.
  1631. */
  1632. maybeToggleRaisedHand() {
  1633. // If we are the dominant speaker, we don't enable "raise hand".
  1634. if (this.isHandRaised || !this.isDominantSpeaker) {
  1635. this.setRaisedHand(!this.isHandRaised);
  1636. }
  1637. },
  1638. /**
  1639. * Sets the local "raised hand" status to a particular value.
  1640. */
  1641. setRaisedHand(raisedHand) {
  1642. if (raisedHand !== this.isHandRaised)
  1643. {
  1644. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1645. this.isHandRaised = raisedHand;
  1646. // Advertise the updated status
  1647. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1648. // Update the view
  1649. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1650. }
  1651. },
  1652. /**
  1653. * Log event to callstats and analytics.
  1654. * @param {string} name the event name
  1655. * @param {int} value the value (it's int because google analytics supports
  1656. * only int).
  1657. * NOTE: Should be used after conference.init
  1658. */
  1659. logEvent(name, value) {
  1660. if(JitsiMeetJS.analytics) {
  1661. JitsiMeetJS.analytics.sendEvent(name, value);
  1662. }
  1663. if(room) {
  1664. room.sendApplicationLog(JSON.stringify({name, value}));
  1665. }
  1666. }
  1667. };