Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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