You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 60KB

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