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 61KB

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