您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 38KB

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