Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 69KB

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