您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 64KB

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