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

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