Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 CQEvents from './service/connectionquality/CQEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. const ConnectionEvents = JitsiMeetJS.events.connection;
  11. const ConnectionErrors = JitsiMeetJS.errors.connection;
  12. const ConferenceEvents = JitsiMeetJS.events.conference;
  13. const ConferenceErrors = JitsiMeetJS.errors.conference;
  14. const TrackEvents = JitsiMeetJS.events.track;
  15. const TrackErrors = JitsiMeetJS.errors.track;
  16. let room, connection, localAudio, localVideo, roomLocker;
  17. /**
  18. * Known custom conference commands.
  19. */
  20. const Commands = {
  21. CONNECTION_QUALITY: "stats",
  22. EMAIL: "email",
  23. ETHERPAD: "etherpad",
  24. PREZI: "prezi",
  25. STOP_PREZI: "stop-prezi"
  26. };
  27. /**
  28. * Open Connection. When authentication failed it shows auth dialog.
  29. * @param roomName the room name to use
  30. * @returns Promise<JitsiConnection>
  31. */
  32. function connect(roomName) {
  33. return openConnection({retry: true, roomName: roomName})
  34. .catch(function (err) {
  35. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  36. APP.UI.notifyTokenAuthFailed();
  37. } else {
  38. APP.UI.notifyConnectionFailed(err);
  39. }
  40. throw err;
  41. });
  42. }
  43. /**
  44. * Share email with other users.
  45. * @param {string} email new email
  46. */
  47. function sendEmail (email) {
  48. room.sendCommand(Commands.EMAIL, {
  49. value: email,
  50. attributes: {
  51. id: room.myUserId()
  52. }
  53. });
  54. }
  55. /**
  56. * Get user nickname by user id.
  57. * @param {string} id user id
  58. * @returns {string?} user nickname or undefined if user is unknown.
  59. */
  60. function getDisplayName (id) {
  61. if (APP.conference.isLocalId(id)) {
  62. return APP.settings.getDisplayName();
  63. }
  64. let participant = room.getParticipantById(id);
  65. if (participant && participant.getDisplayName()) {
  66. return participant.getDisplayName();
  67. }
  68. }
  69. /**
  70. * Mute or unmute local audio stream if it exists.
  71. * @param {boolean} muted if audio stream should be muted or unmuted.
  72. */
  73. function muteLocalAudio (muted) {
  74. if (!localAudio) {
  75. return;
  76. }
  77. if (muted) {
  78. localAudio.mute();
  79. } else {
  80. localAudio.unmute();
  81. }
  82. }
  83. /**
  84. * Mute or unmute local video stream if it exists.
  85. * @param {boolean} muted if video stream should be muted or unmuted.
  86. */
  87. function muteLocalVideo (muted) {
  88. if (!localVideo) {
  89. return;
  90. }
  91. if (muted) {
  92. localVideo.mute();
  93. } else {
  94. localVideo.unmute();
  95. }
  96. }
  97. /**
  98. * Disconnect from the conference and optionally request user feedback.
  99. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  100. */
  101. function hangup (requestFeedback = false) {
  102. let promise = Promise.resolve();
  103. if (requestFeedback) {
  104. promise = APP.UI.requestFeedback();
  105. }
  106. promise.then(function () {
  107. connection.disconnect();
  108. if (!config.enableWelcomePage) {
  109. return;
  110. }
  111. // redirect to welcome page
  112. setTimeout(() => {
  113. APP.settings.setWelcomePageEnabled(true);
  114. window.location.pathname = "/";
  115. }, 3000);
  116. }, function (err) {
  117. console.error('Failed to hangup the call:', err);
  118. });
  119. }
  120. /**
  121. * Create local tracks of specified types.
  122. * @param {string[]} devices required track types ('audio', 'video' etc.)
  123. * @returns {Promise<JitsiLocalTrack[]>}
  124. */
  125. function createLocalTracks (...devices) {
  126. return JitsiMeetJS.createLocalTracks({
  127. // copy array to avoid mutations inside library
  128. devices: devices.slice(0),
  129. resolution: config.resolution,
  130. cameraDeviceId: APP.settings.getCameraDeviceId(),
  131. micDeviceId: APP.settings.getMicDeviceId(),
  132. // adds any ff fake device settings if any
  133. firefox_fake_device: config.firefox_fake_device
  134. }).catch(function (err) {
  135. console.error('failed to create local tracks', ...devices, err);
  136. return Promise.reject(err);
  137. });
  138. }
  139. /**
  140. * Create local screen sharing track.
  141. * Shows UI notification if Firefox extension is required.
  142. * @returns {Promise<JitsiLocalTrack[]>}
  143. */
  144. function createDesktopTrack () {
  145. return createLocalTracks('desktop').catch(function (err) {
  146. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  147. APP.UI.showExtensionRequiredDialog(
  148. config.desktopSharingFirefoxExtensionURL
  149. );
  150. }
  151. return Promise.reject(err);
  152. });
  153. }
  154. class ConferenceConnector {
  155. constructor(resolve, reject) {
  156. this._resolve = resolve;
  157. this._reject = reject;
  158. this.reconnectTimeout = null;
  159. room.on(ConferenceEvents.CONFERENCE_JOINED,
  160. this._handleConferenceJoined.bind(this));
  161. room.on(ConferenceEvents.CONFERENCE_FAILED,
  162. this._onConferenceFailed.bind(this));
  163. room.on(ConferenceEvents.CONFERENCE_ERROR,
  164. this._onConferenceError.bind(this));
  165. }
  166. _handleConferenceFailed(err, msg) {
  167. this._unsubscribe();
  168. this._reject(err);
  169. }
  170. _onConferenceFailed(err, ...params) {
  171. console.error('CONFERENCE FAILED:', err, ...params);
  172. switch (err) {
  173. // room is locked by the password
  174. case ConferenceErrors.PASSWORD_REQUIRED:
  175. APP.UI.markRoomLocked(true);
  176. roomLocker.requirePassword().then(function () {
  177. room.join(roomLocker.password);
  178. });
  179. break;
  180. case ConferenceErrors.CONNECTION_ERROR:
  181. {
  182. let [msg] = params;
  183. APP.UI.notifyConnectionFailed(msg);
  184. }
  185. break;
  186. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  187. APP.UI.notifyBridgeDown();
  188. break;
  189. // not enough rights to create conference
  190. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  191. // schedule reconnect to check if someone else created the room
  192. this.reconnectTimeout = setTimeout(function () {
  193. room.join();
  194. }, 5000);
  195. // notify user that auth is required
  196. AuthHandler.requireAuth(room, roomLocker.password);
  197. break;
  198. case ConferenceErrors.RESERVATION_ERROR:
  199. {
  200. let [code, msg] = params;
  201. APP.UI.notifyReservationError(code, msg);
  202. }
  203. break;
  204. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  205. APP.UI.notifyGracefulShutdown();
  206. break;
  207. case ConferenceErrors.JINGLE_FATAL_ERROR:
  208. APP.UI.notifyInternalError();
  209. break;
  210. case ConferenceErrors.CONFERENCE_DESTROYED:
  211. {
  212. let [reason] = params;
  213. APP.UI.hideStats();
  214. APP.UI.notifyConferenceDestroyed(reason);
  215. }
  216. break;
  217. case ConferenceErrors.FOCUS_DISCONNECTED:
  218. {
  219. let [focus, retrySec] = params;
  220. APP.UI.notifyFocusDisconnected(focus, retrySec);
  221. }
  222. break;
  223. case ConferenceErrors.FOCUS_LEFT:
  224. room.leave().then(() => connection.disconnect());
  225. APP.UI.notifyFocusLeft();
  226. break;
  227. default:
  228. this._handleConferenceFailed(err, ...params);
  229. }
  230. }
  231. _onConferenceError(err, ...params) {
  232. console.error('CONFERENCE Error:', err, params);
  233. switch (err) {
  234. case ConferenceErrors.CHAT_ERROR:
  235. {
  236. let [code, msg] = params;
  237. APP.UI.showChatError(code, msg);
  238. }
  239. break;
  240. default:
  241. console.error("Unknown error.");
  242. }
  243. }
  244. _unsubscribe() {
  245. room.off(
  246. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  247. room.off(
  248. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  249. if (this.reconnectTimeout !== null) {
  250. clearTimeout(this.reconnectTimeout);
  251. }
  252. AuthHandler.closeAuth();
  253. }
  254. _handleConferenceJoined() {
  255. this._unsubscribe();
  256. this._resolve();
  257. }
  258. connect() {
  259. room.join();
  260. }
  261. }
  262. export default {
  263. localId: undefined,
  264. isModerator: false,
  265. audioMuted: false,
  266. videoMuted: false,
  267. isSharingScreen: false,
  268. isDesktopSharingEnabled: false,
  269. /**
  270. * Open new connection and join to the conference.
  271. * @param {object} options
  272. * @param {string} roomName name of the conference
  273. * @returns {Promise}
  274. */
  275. init(options) {
  276. this.roomName = options.roomName;
  277. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  278. return JitsiMeetJS.init(config).then(() => {
  279. return Promise.all([
  280. // try to retrieve audio and video
  281. createLocalTracks('audio', 'video')
  282. // if failed then try to retrieve only audio
  283. .catch(() => createLocalTracks('audio'))
  284. // if audio also failed then just return empty array
  285. .catch(() => []),
  286. connect(options.roomName)
  287. ]);
  288. }).then(([tracks, con]) => {
  289. console.log('initialized with %s local tracks', tracks.length);
  290. connection = con;
  291. this._createRoom(tracks);
  292. this.isDesktopSharingEnabled =
  293. JitsiMeetJS.isDesktopSharingEnabled();
  294. // update list of available devices
  295. if (JitsiMeetJS.isDeviceListAvailable() &&
  296. JitsiMeetJS.isDeviceChangeAvailable()) {
  297. JitsiMeetJS.enumerateDevices((devices) => {
  298. this.availableDevices = devices;
  299. APP.UI.onAvailableDevicesChanged();
  300. });
  301. }
  302. // XXX The API will take care of disconnecting from the XMPP server
  303. // (and, thus, leaving the room) on unload.
  304. return new Promise((resolve, reject) => {
  305. (new ConferenceConnector(resolve, reject)).connect();
  306. });
  307. });
  308. },
  309. /**
  310. * Check if id is id of the local user.
  311. * @param {string} id id to check
  312. * @returns {boolean}
  313. */
  314. isLocalId (id) {
  315. return this.localId === id;
  316. },
  317. /**
  318. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  319. * @param mute true for mute and false for unmute.
  320. */
  321. muteAudio (mute) {
  322. muteLocalAudio(mute);
  323. },
  324. /**
  325. * Returns whether local audio is muted or not.
  326. * @returns {boolean}
  327. */
  328. isLocalAudioMuted() {
  329. return this.audioMuted;
  330. },
  331. /**
  332. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  333. */
  334. toggleAudioMuted () {
  335. this.muteAudio(!this.audioMuted);
  336. },
  337. /**
  338. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  339. * @param mute true for mute and false for unmute.
  340. */
  341. muteVideo (mute) {
  342. muteLocalVideo(mute);
  343. },
  344. /**
  345. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  346. */
  347. toggleVideoMuted () {
  348. this.muteVideo(!this.videoMuted);
  349. },
  350. /**
  351. * Retrieve list of conference participants (without local user).
  352. * @returns {JitsiParticipant[]}
  353. */
  354. listMembers () {
  355. return room.getParticipants();
  356. },
  357. /**
  358. * Retrieve list of ids of conference participants (without local user).
  359. * @returns {string[]}
  360. */
  361. listMembersIds () {
  362. return room.getParticipants().map(p => p.getId());
  363. },
  364. /**
  365. * List of available cameras and microphones.
  366. */
  367. availableDevices: [],
  368. /**
  369. * Check if SIP is supported.
  370. * @returns {boolean}
  371. */
  372. sipGatewayEnabled () {
  373. return room.isSIPCallingSupported();
  374. },
  375. get membersCount () {
  376. return room.getParticipants().length + 1;
  377. },
  378. get startAudioMuted () {
  379. return room && room.getStartMutedPolicy().audio;
  380. },
  381. get startVideoMuted () {
  382. return room && room.getStartMutedPolicy().video;
  383. },
  384. /**
  385. * Returns true if the callstats integration is enabled, otherwise returns
  386. * false.
  387. *
  388. * @returns true if the callstats integration is enabled, otherwise returns
  389. * false.
  390. */
  391. isCallstatsEnabled () {
  392. return room.isCallstatsEnabled();
  393. },
  394. /**
  395. * Sends the given feedback through CallStats if enabled.
  396. *
  397. * @param overallFeedback an integer between 1 and 5 indicating the
  398. * user feedback
  399. * @param detailedFeedback detailed feedback from the user. Not yet used
  400. */
  401. sendFeedback (overallFeedback, detailedFeedback) {
  402. return room.sendFeedback (overallFeedback, detailedFeedback);
  403. },
  404. // used by torture currently
  405. isJoined () {
  406. return this._room
  407. && this._room.isJoined();
  408. },
  409. getConnectionState () {
  410. return this._room
  411. && this._room.getConnectionState();
  412. },
  413. getMyUserId () {
  414. return this._room
  415. && this._room.myUserId();
  416. },
  417. /**
  418. * Will be filled with values only when config.debug is enabled.
  419. * Its used by torture to check audio levels.
  420. */
  421. audioLevelsMap: {},
  422. /**
  423. * Returns the stored audio level (stored only if config.debug is enabled)
  424. * @param id the id for the user audio level to return (the id value is
  425. * returned for the participant using getMyUserId() method)
  426. */
  427. getPeerSSRCAudioLevel (id) {
  428. return this.audioLevelsMap[id];
  429. },
  430. /**
  431. * Will check for number of remote particiapnts that have at least one
  432. * remote track.
  433. * @return {boolean} whether we have enough participants with remote streams
  434. */
  435. checkEnoughParticipants (number) {
  436. var participants = this._room.getParticipants();
  437. var foundParticipants = 0;
  438. for (var i = 0; i < participants.length; i += 1) {
  439. if (participants[i].getTracks().length > 0) {
  440. foundParticipants++;
  441. }
  442. }
  443. return foundParticipants >= number;
  444. },
  445. /**
  446. * Returns the stats.
  447. */
  448. getStats() {
  449. return ConnectionQuality.getStats();
  450. },
  451. // end used by torture
  452. getLogs () {
  453. return room.getLogs();
  454. },
  455. _createRoom (localTracks) {
  456. room = connection.initJitsiConference(APP.conference.roomName,
  457. this._getConferenceOptions());
  458. this.localId = room.myUserId();
  459. localTracks.forEach((track) => {
  460. if (track.isAudioTrack()) {
  461. this.useAudioStream(track);
  462. } else if (track.isVideoTrack()) {
  463. this.useVideoStream(track);
  464. }
  465. });
  466. roomLocker = createRoomLocker(room);
  467. this._room = room; // FIXME do not use this
  468. let email = APP.settings.getEmail();
  469. email && sendEmail(email);
  470. let nick = APP.settings.getDisplayName();
  471. if (config.useNicks && !nick) {
  472. nick = APP.UI.askForNickname();
  473. APP.settings.setDisplayName(nick);
  474. }
  475. nick && room.setDisplayName(nick);
  476. this._setupListeners();
  477. },
  478. _getConferenceOptions() {
  479. let options = config;
  480. if(config.enableRecording) {
  481. options.recordingType = (config.hosts &&
  482. (typeof config.hosts.jirecon != "undefined"))?
  483. "jirecon" : "colibri";
  484. }
  485. return options;
  486. },
  487. /**
  488. * Start using provided video stream.
  489. * Stops previous video stream.
  490. * @param {JitsiLocalTrack} [stream] new stream to use or null
  491. * @returns {Promise}
  492. */
  493. useVideoStream (stream) {
  494. let promise = Promise.resolve();
  495. if (localVideo) {
  496. // this calls room.removeTrack internally
  497. // so we don't need to remove it manually
  498. promise = localVideo.stop();
  499. }
  500. localVideo = stream;
  501. return promise.then(function () {
  502. if (stream) {
  503. return room.addTrack(stream);
  504. }
  505. }).then(() => {
  506. if (stream) {
  507. this.videoMuted = stream.isMuted();
  508. this.isSharingScreen = stream.videoType === 'desktop';
  509. APP.UI.addLocalStream(stream);
  510. } else {
  511. this.videoMuted = false;
  512. this.isSharingScreen = false;
  513. }
  514. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  515. APP.UI.updateDesktopSharingButtons();
  516. });
  517. },
  518. /**
  519. * Start using provided audio stream.
  520. * Stops previous audio stream.
  521. * @param {JitsiLocalTrack} [stream] new stream to use or null
  522. * @returns {Promise}
  523. */
  524. useAudioStream (stream) {
  525. let promise = Promise.resolve();
  526. if (localAudio) {
  527. // this calls room.removeTrack internally
  528. // so we don't need to remove it manually
  529. promise = localAudio.stop();
  530. }
  531. localAudio = stream;
  532. return promise.then(function () {
  533. if (stream) {
  534. return room.addTrack(stream);
  535. }
  536. }).then(() => {
  537. if (stream) {
  538. this.audioMuted = stream.isMuted();
  539. APP.UI.addLocalStream(stream);
  540. } else {
  541. this.audioMuted = false;
  542. }
  543. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  544. });
  545. },
  546. videoSwitchInProgress: false,
  547. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  548. if (this.videoSwitchInProgress) {
  549. console.warn("Switch in progress.");
  550. return;
  551. }
  552. if (!this.isDesktopSharingEnabled) {
  553. console.warn("Cannot toggle screen sharing: not supported.");
  554. return;
  555. }
  556. this.videoSwitchInProgress = true;
  557. if (shareScreen) {
  558. createDesktopTrack().then(([stream]) => {
  559. stream.on(
  560. TrackEvents.TRACK_STOPPED,
  561. () => {
  562. // if stream was stopped during screensharing session
  563. // then we should switch to video
  564. // otherwise we stopped it because we already switched
  565. // to video, so nothing to do here
  566. if (this.isSharingScreen) {
  567. this.toggleScreenSharing(false);
  568. }
  569. }
  570. );
  571. return this.useVideoStream(stream);
  572. }).then(() => {
  573. this.videoSwitchInProgress = false;
  574. console.log('sharing local desktop');
  575. }).catch((err) => {
  576. this.videoSwitchInProgress = false;
  577. this.toggleScreenSharing(false);
  578. console.error('failed to share local desktop', err);
  579. });
  580. } else {
  581. createLocalTracks('video').then(
  582. ([stream]) => this.useVideoStream(stream)
  583. ).then(() => {
  584. this.videoSwitchInProgress = false;
  585. console.log('sharing local video');
  586. }).catch((err) => {
  587. this.useVideoStream(null);
  588. this.videoSwitchInProgress = false;
  589. console.error('failed to share local video', err);
  590. });
  591. }
  592. },
  593. /**
  594. * Setup interaction between conference and UI.
  595. */
  596. _setupListeners () {
  597. // add local streams when joined to the conference
  598. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  599. APP.UI.mucJoined();
  600. });
  601. room.on(
  602. ConferenceEvents.AUTH_STATUS_CHANGED,
  603. function (authEnabled, authLogin) {
  604. APP.UI.updateAuthInfo(authEnabled, authLogin);
  605. }
  606. );
  607. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  608. console.log('USER %s connnected', id, user);
  609. APP.API.notifyUserJoined(id);
  610. // FIXME email???
  611. APP.UI.addUser(id, user.getDisplayName());
  612. // chek the roles for the new user and reflect them
  613. APP.UI.updateUserRole(user);
  614. });
  615. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  616. console.log('USER %s LEFT', id, user);
  617. APP.API.notifyUserLeft(id);
  618. APP.UI.removeUser(id, user.getDisplayName());
  619. APP.UI.stopPrezi(id);
  620. });
  621. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  622. if (this.isLocalId(id)) {
  623. console.info(`My role changed, new role: ${role}`);
  624. this.isModerator = room.isModerator();
  625. APP.UI.updateLocalRole(room.isModerator());
  626. } else {
  627. let user = room.getParticipantById(id);
  628. if (user) {
  629. APP.UI.updateUserRole(user);
  630. }
  631. }
  632. });
  633. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  634. if(!track || track.isLocal())
  635. return;
  636. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  637. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  638. });
  639. APP.UI.addRemoteStream(track);
  640. });
  641. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  642. if(!track || track.isLocal())
  643. return;
  644. APP.UI.removeRemoteStream(track);
  645. });
  646. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  647. if(!track)
  648. return;
  649. const handler = (track.getType() === "audio")?
  650. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  651. let id;
  652. const mute = track.isMuted();
  653. if(track.isLocal()){
  654. id = this.localId;
  655. if(track.getType() === "audio") {
  656. this.audioMuted = mute;
  657. } else {
  658. this.videoMuted = mute;
  659. }
  660. } else {
  661. id = track.getParticipantId();
  662. }
  663. handler(id , mute);
  664. });
  665. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  666. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  667. lvl = 0;
  668. }
  669. if(config.debug)
  670. {
  671. this.audioLevelsMap[id] = lvl;
  672. console.log("AudioLevel:" + id + "/" + lvl);
  673. }
  674. APP.UI.setAudioLevel(id, lvl);
  675. });
  676. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  677. //FIXME
  678. if (config.muteLocalVideoIfNotInLastN) {
  679. // TODO mute or unmute if required
  680. // mark video on UI
  681. // APP.UI.markVideoMuted(true/false);
  682. }
  683. });
  684. room.on(
  685. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  686. APP.UI.handleLastNEndpoints(ids, enteringIds);
  687. });
  688. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  689. APP.UI.markDominantSpeaker(id);
  690. });
  691. if (!interfaceConfig.filmStripOnly) {
  692. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  693. APP.UI.markVideoInterrupted(true);
  694. });
  695. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  696. APP.UI.markVideoInterrupted(false);
  697. });
  698. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  699. let nick = getDisplayName(id);
  700. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  701. APP.UI.addMessage(id, nick, text, ts);
  702. });
  703. }
  704. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  705. APP.API.notifyDisplayNameChanged(id, displayName);
  706. APP.UI.changeDisplayName(id, displayName);
  707. });
  708. room.on(ConferenceEvents.RECORDING_STATE_CHANGED, (status, error) => {
  709. if(status == "error") {
  710. console.error(error);
  711. return;
  712. }
  713. APP.UI.updateRecordingState(status);
  714. });
  715. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  716. APP.UI.updateUserStatus(id, status);
  717. });
  718. room.on(ConferenceEvents.KICKED, () => {
  719. APP.UI.hideStats();
  720. APP.UI.notifyKicked();
  721. // FIXME close
  722. });
  723. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  724. APP.UI.updateDTMFSupport(isDTMFSupported);
  725. });
  726. room.on(ConferenceEvents.FIREFOX_EXTENSION_NEEDED, function (url) {
  727. APP.UI.notifyFirefoxExtensionRequired(url);
  728. });
  729. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  730. if (room.isModerator()) {
  731. let promise = roomLocker.isLocked
  732. ? roomLocker.askToUnlock()
  733. : roomLocker.askToLock();
  734. promise.then(() => {
  735. APP.UI.markRoomLocked(roomLocker.isLocked);
  736. });
  737. } else {
  738. roomLocker.notifyModeratorRequired();
  739. }
  740. });
  741. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  742. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  743. if (!interfaceConfig.filmStripOnly) {
  744. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  745. APP.API.notifySendingChatMessage(message);
  746. room.sendTextMessage(message);
  747. });
  748. }
  749. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  750. ConnectionQuality.updateLocalStats(stats);
  751. });
  752. ConnectionQuality.addListener(
  753. CQEvents.LOCALSTATS_UPDATED,
  754. (percent, stats) => {
  755. APP.UI.updateLocalStats(percent, stats);
  756. // send local stats to other users
  757. room.sendCommandOnce(Commands.CONNECTION_QUALITY, {
  758. children: ConnectionQuality.convertToMUCStats(stats),
  759. attributes: {
  760. xmlns: 'http://jitsi.org/jitmeet/stats'
  761. }
  762. });
  763. }
  764. );
  765. // listen to remote stats
  766. room.addCommandListener(Commands.CONNECTION_QUALITY,(values, from) => {
  767. ConnectionQuality.updateRemoteStats(from, values);
  768. });
  769. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  770. (id, percent, stats) => {
  771. APP.UI.updateRemoteStats(id, percent, stats);
  772. });
  773. room.addCommandListener(Commands.ETHERPAD, ({value}) => {
  774. APP.UI.initEtherpad(value);
  775. });
  776. room.addCommandListener(Commands.PREZI, ({value, attributes}) => {
  777. APP.UI.showPrezi(attributes.id, value, attributes.slide);
  778. });
  779. room.addCommandListener(Commands.STOP_PREZI, ({attributes}) => {
  780. APP.UI.stopPrezi(attributes.id);
  781. });
  782. APP.UI.addListener(UIEvents.SHARE_PREZI, (url, slide) => {
  783. console.log('Sharing Prezi %s slide %s', url, slide);
  784. room.removeCommand(Commands.PREZI);
  785. room.sendCommand(Commands.PREZI, {
  786. value: url,
  787. attributes: {
  788. id: room.myUserId(),
  789. slide
  790. }
  791. });
  792. });
  793. APP.UI.addListener(UIEvents.STOP_SHARING_PREZI, () => {
  794. room.removeCommand(Commands.PREZI);
  795. room.sendCommandOnce(Commands.STOP_PREZI, {
  796. attributes: {
  797. id: room.myUserId()
  798. }
  799. });
  800. });
  801. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email) => {
  802. APP.settings.setEmail(email);
  803. APP.UI.setUserAvatar(room.myUserId(), email);
  804. sendEmail(email);
  805. });
  806. room.addCommandListener(Commands.EMAIL, (data) => {
  807. APP.UI.setUserAvatar(data.attributes.id, data.value);
  808. });
  809. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  810. nickname = nickname.trim();
  811. if (nickname === APP.settings.getDisplayName()) {
  812. return;
  813. }
  814. APP.settings.setDisplayName(nickname);
  815. room.setDisplayName(nickname);
  816. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  817. });
  818. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  819. (startAudioMuted, startVideoMuted) => {
  820. room.setStartMutedPolicy({audio: startAudioMuted,
  821. video: startVideoMuted});
  822. }
  823. );
  824. room.on(
  825. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  826. (policy) => {
  827. APP.UI.onStartMutedChanged();
  828. }
  829. );
  830. room.on(ConferenceEvents.STARTED_MUTED, () => {
  831. (room.isStartAudioMuted() || room.isStartVideoMuted())
  832. && APP.UI.notifyInitiallyMuted();
  833. });
  834. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  835. APP.UI.inviteParticipants(
  836. roomUrl,
  837. APP.conference.roomName,
  838. roomLocker.password,
  839. APP.settings.getDisplayName()
  840. );
  841. });
  842. room.on(
  843. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  844. APP.UI.updateDevicesAvailability(id, devices);
  845. }
  846. );
  847. // call hangup
  848. APP.UI.addListener(UIEvents.HANGUP, () => {
  849. hangup(true);
  850. });
  851. // logout
  852. APP.UI.addListener(UIEvents.LOGOUT, () => {
  853. AuthHandler.logout(room).then(function (url) {
  854. if (url) {
  855. window.location.href = url;
  856. } else {
  857. hangup(true);
  858. }
  859. });
  860. });
  861. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  862. room.dial(sipNumber);
  863. });
  864. // Starts or stops the recording for the conference.
  865. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, (predefinedToken) => {
  866. if (predefinedToken) {
  867. room.toggleRecording({token: predefinedToken});
  868. return;
  869. }
  870. APP.UI.requestRecordingToken().then((token) => {
  871. room.toggleRecording({token: token});
  872. });
  873. });
  874. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  875. room.setSubject(topic);
  876. });
  877. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  878. APP.UI.setSubject(subject);
  879. });
  880. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  881. room.kickParticipant(id);
  882. });
  883. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  884. room.muteParticipant(id);
  885. });
  886. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  887. AuthHandler.authenticate(room);
  888. });
  889. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  890. room.selectParticipant(id);
  891. });
  892. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (id) => {
  893. room.pinParticipant(id);
  894. });
  895. APP.UI.addListener(
  896. UIEvents.VIDEO_DEVICE_CHANGED,
  897. (cameraDeviceId) => {
  898. APP.settings.setCameraDeviceId(cameraDeviceId);
  899. createLocalTracks('video').then(([stream]) => {
  900. this.useVideoStream(stream);
  901. console.log('switched local video device');
  902. });
  903. }
  904. );
  905. APP.UI.addListener(
  906. UIEvents.AUDIO_DEVICE_CHANGED,
  907. (micDeviceId) => {
  908. APP.settings.setMicDeviceId(micDeviceId);
  909. createLocalTracks('audio').then(([stream]) => {
  910. this.useAudioStream(stream);
  911. console.log('switched local audio device');
  912. });
  913. }
  914. );
  915. APP.UI.addListener(
  916. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  917. );
  918. }
  919. };