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

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