Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 55KB

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