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 67KB

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