You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 62KB

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