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

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