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.

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