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

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