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

conference.js 62KB

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