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

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