Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 60KB

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