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

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