Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 65KB

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