Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 71KB

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