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

conference.js 58KB

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