You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 74KB

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