Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 56KB

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