您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 68KB

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