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

conference.js 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. * Will be filled with values only when config.debug is enabled.
  429. * Its used by torture to check audio levels.
  430. */
  431. audioLevelsMap: {},
  432. /**
  433. * Returns the stored audio level (stored only if config.debug is enabled)
  434. * @param id the id for the user audio level to return (the id value is
  435. * returned for the participant using getMyUserId() method)
  436. */
  437. getPeerSSRCAudioLevel (id) {
  438. return this.audioLevelsMap[id];
  439. },
  440. /**
  441. * Will check for number of remote particiapnts that have at least one
  442. * remote track.
  443. * @return {boolean} whether we have enough participants with remote streams
  444. */
  445. checkEnoughParticipants (number) {
  446. var participants = this._room.getParticipants();
  447. var foundParticipants = 0;
  448. for (var i = 0; i < participants.length; i += 1) {
  449. if (participants[i].getTracks().length > 0) {
  450. foundParticipants++;
  451. }
  452. }
  453. return foundParticipants >= number;
  454. },
  455. /**
  456. * Returns the stats.
  457. */
  458. getStats() {
  459. return ConnectionQuality.getStats();
  460. },
  461. // end used by torture
  462. getLogs () {
  463. return room.getLogs();
  464. },
  465. /**
  466. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  467. * desire to keep room private to this instance and (2) the need of other
  468. * modules to send and receive commands to and from participants.
  469. * Eventually, this instance remains in control with respect to the
  470. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  471. * JitsiConference) is to be used in the implementation of the Command(s)
  472. * API of this instance.
  473. */
  474. commands: {
  475. /**
  476. * Known custom conference commands.
  477. */
  478. defaults: {
  479. CONNECTION_QUALITY: "stats",
  480. EMAIL: "email",
  481. ETHERPAD: "etherpad",
  482. SHARED_VIDEO: "shared-video",
  483. CUSTOM_ROLE: "custom-role"
  484. },
  485. /**
  486. * Receives notifications from other participants about commands aka
  487. * custom events (sent by sendCommand or sendCommandOnce methods).
  488. * @param command {String} the name of the command
  489. * @param handler {Function} handler for the command
  490. */
  491. addCommandListener () {
  492. room.addCommandListener.apply(room, arguments);
  493. },
  494. /**
  495. * Removes command.
  496. * @param name {String} the name of the command.
  497. */
  498. removeCommand () {
  499. room.removeCommand.apply(room, arguments);
  500. },
  501. /**
  502. * Sends command.
  503. * @param name {String} the name of the command.
  504. * @param values {Object} with keys and values that will be sent.
  505. */
  506. sendCommand () {
  507. room.sendCommand.apply(room, arguments);
  508. },
  509. /**
  510. * Sends command one time.
  511. * @param name {String} the name of the command.
  512. * @param values {Object} with keys and values that will be sent.
  513. */
  514. sendCommandOnce () {
  515. room.sendCommandOnce.apply(room, arguments);
  516. }
  517. },
  518. _createRoom (localTracks) {
  519. room = connection.initJitsiConference(APP.conference.roomName,
  520. this._getConferenceOptions());
  521. this.localId = room.myUserId();
  522. localTracks.forEach((track) => {
  523. if (track.isAudioTrack()) {
  524. this.useAudioStream(track);
  525. } else if (track.isVideoTrack()) {
  526. this.useVideoStream(track);
  527. }
  528. });
  529. roomLocker = createRoomLocker(room);
  530. this._room = room; // FIXME do not use this
  531. let email = APP.settings.getEmail();
  532. email && sendEmail(this.commands.defaults.EMAIL, email);
  533. let nick = APP.settings.getDisplayName();
  534. if (config.useNicks && !nick) {
  535. nick = APP.UI.askForNickname();
  536. APP.settings.setDisplayName(nick);
  537. }
  538. nick && room.setDisplayName(nick);
  539. this._setupListeners();
  540. },
  541. _getConferenceOptions() {
  542. let options = config;
  543. if(config.enableRecording && !config.recordingType) {
  544. options.recordingType = (config.hosts &&
  545. (typeof config.hosts.jirecon != "undefined"))?
  546. "jirecon" : "colibri";
  547. }
  548. return options;
  549. },
  550. /**
  551. * Start using provided video stream.
  552. * Stops previous video stream.
  553. * @param {JitsiLocalTrack} [stream] new stream to use or null
  554. * @returns {Promise}
  555. */
  556. useVideoStream (stream) {
  557. let promise = Promise.resolve();
  558. if (localVideo) {
  559. // this calls room.removeTrack internally
  560. // so we don't need to remove it manually
  561. promise = localVideo.dispose();
  562. }
  563. localVideo = stream;
  564. return promise.then(function () {
  565. if (stream) {
  566. return room.addTrack(stream);
  567. }
  568. }).then(() => {
  569. if (stream) {
  570. this.videoMuted = stream.isMuted();
  571. this.isSharingScreen = stream.videoType === 'desktop';
  572. APP.UI.addLocalStream(stream);
  573. } else {
  574. this.videoMuted = false;
  575. this.isSharingScreen = false;
  576. }
  577. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  578. APP.UI.updateDesktopSharingButtons();
  579. });
  580. },
  581. /**
  582. * Start using provided audio stream.
  583. * Stops previous audio stream.
  584. * @param {JitsiLocalTrack} [stream] new stream to use or null
  585. * @returns {Promise}
  586. */
  587. useAudioStream (stream) {
  588. let promise = Promise.resolve();
  589. if (localAudio) {
  590. // this calls room.removeTrack internally
  591. // so we don't need to remove it manually
  592. promise = localAudio.dispose();
  593. }
  594. localAudio = stream;
  595. return promise.then(function () {
  596. if (stream) {
  597. return room.addTrack(stream);
  598. }
  599. }).then(() => {
  600. if (stream) {
  601. this.audioMuted = stream.isMuted();
  602. APP.UI.addLocalStream(stream);
  603. } else {
  604. this.audioMuted = false;
  605. }
  606. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  607. });
  608. },
  609. videoSwitchInProgress: false,
  610. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  611. if (this.videoSwitchInProgress) {
  612. console.warn("Switch in progress.");
  613. return;
  614. }
  615. if (!this.isDesktopSharingEnabled) {
  616. console.warn("Cannot toggle screen sharing: not supported.");
  617. return;
  618. }
  619. this.videoSwitchInProgress = true;
  620. if (shareScreen) {
  621. createLocalTracks('desktop').then(([stream]) => {
  622. stream.on(
  623. TrackEvents.LOCAL_TRACK_STOPPED,
  624. () => {
  625. // if stream was stopped during screensharing session
  626. // then we should switch to video
  627. // otherwise we stopped it because we already switched
  628. // to video, so nothing to do here
  629. if (this.isSharingScreen) {
  630. this.toggleScreenSharing(false);
  631. }
  632. }
  633. );
  634. return this.useVideoStream(stream);
  635. }).then(() => {
  636. this.videoSwitchInProgress = false;
  637. console.log('sharing local desktop');
  638. }).catch((err) => {
  639. this.videoSwitchInProgress = false;
  640. this.toggleScreenSharing(false);
  641. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  642. return;
  643. console.error('failed to share local desktop', err);
  644. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  645. APP.UI.showExtensionRequiredDialog(
  646. config.desktopSharingFirefoxExtensionURL
  647. );
  648. return;
  649. }
  650. // Handling:
  651. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  652. // TrackErrors.GENERAL
  653. // and any other
  654. let dialogTxt = APP.translation
  655. .generateTranslationHTML("dialog.failtoinstall");
  656. let dialogTitle = APP.translation
  657. .generateTranslationHTML("dialog.error");
  658. APP.UI.messageHandler.openDialog(
  659. dialogTitle,
  660. dialogTxt,
  661. false
  662. );
  663. });
  664. } else {
  665. createLocalTracks('video').then(
  666. ([stream]) => this.useVideoStream(stream)
  667. ).then(() => {
  668. this.videoSwitchInProgress = false;
  669. console.log('sharing local video');
  670. }).catch((err) => {
  671. this.useVideoStream(null);
  672. this.videoSwitchInProgress = false;
  673. console.error('failed to share local video', err);
  674. });
  675. }
  676. },
  677. /**
  678. * Setup interaction between conference and UI.
  679. */
  680. _setupListeners () {
  681. // add local streams when joined to the conference
  682. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  683. APP.UI.mucJoined();
  684. });
  685. room.on(
  686. ConferenceEvents.AUTH_STATUS_CHANGED,
  687. function (authEnabled, authLogin) {
  688. APP.UI.updateAuthInfo(authEnabled, authLogin);
  689. }
  690. );
  691. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  692. console.log('USER %s connnected', id, user);
  693. APP.API.notifyUserJoined(id);
  694. APP.UI.addUser(id, user.getDisplayName());
  695. // chek the roles for the new user and reflect them
  696. APP.UI.updateUserRole(user);
  697. });
  698. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  699. console.log('USER %s LEFT', id, user);
  700. APP.API.notifyUserLeft(id);
  701. APP.UI.removeUser(id, user.getDisplayName());
  702. APP.UI.stopSharedVideo(id);
  703. });
  704. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  705. if (this.isLocalId(id)) {
  706. console.info(`My role changed, new role: ${role}`);
  707. this.isModerator = room.isModerator();
  708. APP.UI.updateLocalRole(room.isModerator());
  709. } else {
  710. let user = room.getParticipantById(id);
  711. if (user) {
  712. APP.UI.updateUserRole(user);
  713. }
  714. }
  715. });
  716. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  717. if(!track || track.isLocal())
  718. return;
  719. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  720. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  721. });
  722. APP.UI.addRemoteStream(track);
  723. });
  724. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  725. if(!track || track.isLocal())
  726. return;
  727. APP.UI.removeRemoteStream(track);
  728. });
  729. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  730. if(!track)
  731. return;
  732. const handler = (track.getType() === "audio")?
  733. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  734. let id;
  735. const mute = track.isMuted();
  736. if(track.isLocal()){
  737. id = this.localId;
  738. if(track.getType() === "audio") {
  739. this.audioMuted = mute;
  740. } else {
  741. this.videoMuted = mute;
  742. }
  743. } else {
  744. id = track.getParticipantId();
  745. }
  746. handler(id , mute);
  747. });
  748. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  749. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  750. lvl = 0;
  751. }
  752. if(config.debug)
  753. {
  754. this.audioLevelsMap[id] = lvl;
  755. console.log("AudioLevel:" + id + "/" + lvl);
  756. }
  757. APP.UI.setAudioLevel(id, lvl);
  758. });
  759. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  760. //FIXME
  761. if (config.muteLocalVideoIfNotInLastN) {
  762. // TODO mute or unmute if required
  763. // mark video on UI
  764. // APP.UI.markVideoMuted(true/false);
  765. }
  766. });
  767. room.on(
  768. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  769. APP.UI.handleLastNEndpoints(ids, enteringIds);
  770. });
  771. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  772. APP.UI.markDominantSpeaker(id);
  773. });
  774. if (!interfaceConfig.filmStripOnly) {
  775. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  776. APP.UI.markVideoInterrupted(true);
  777. });
  778. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  779. APP.UI.markVideoInterrupted(false);
  780. });
  781. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  782. let nick = getDisplayName(id);
  783. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  784. APP.UI.addMessage(id, nick, text, ts);
  785. });
  786. }
  787. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  788. APP.API.notifyDisplayNameChanged(id, displayName);
  789. APP.UI.changeDisplayName(id, displayName);
  790. });
  791. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  792. console.log("Received recorder status change: ", status, error);
  793. if(status == "error") {
  794. console.error(error);
  795. return;
  796. }
  797. APP.UI.updateRecordingState(status);
  798. });
  799. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  800. APP.UI.updateUserStatus(id, status);
  801. });
  802. room.on(ConferenceEvents.KICKED, () => {
  803. APP.UI.hideStats();
  804. APP.UI.notifyKicked();
  805. // FIXME close
  806. });
  807. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  808. APP.UI.updateDTMFSupport(isDTMFSupported);
  809. });
  810. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  811. if (room.isModerator()) {
  812. let promise = roomLocker.isLocked
  813. ? roomLocker.askToUnlock()
  814. : roomLocker.askToLock();
  815. promise.then(() => {
  816. APP.UI.markRoomLocked(roomLocker.isLocked);
  817. });
  818. } else {
  819. roomLocker.notifyModeratorRequired();
  820. }
  821. });
  822. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  823. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  824. if (!interfaceConfig.filmStripOnly) {
  825. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  826. APP.API.notifySendingChatMessage(message);
  827. room.sendTextMessage(message);
  828. });
  829. }
  830. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  831. ConnectionQuality.updateLocalStats(stats);
  832. });
  833. ConnectionQuality.addListener(
  834. CQEvents.LOCALSTATS_UPDATED,
  835. (percent, stats) => {
  836. APP.UI.updateLocalStats(percent, stats);
  837. // send local stats to other users
  838. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  839. {
  840. children: ConnectionQuality.convertToMUCStats(stats),
  841. attributes: {
  842. xmlns: 'http://jitsi.org/jitmeet/stats'
  843. }
  844. });
  845. }
  846. );
  847. // listen to remote stats
  848. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  849. (values, from) => {
  850. ConnectionQuality.updateRemoteStats(from, values);
  851. });
  852. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  853. (id, percent, stats) => {
  854. APP.UI.updateRemoteStats(id, percent, stats);
  855. });
  856. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  857. APP.UI.initEtherpad(value);
  858. });
  859. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  860. email = email.trim();
  861. if (email === APP.settings.getEmail()) {
  862. return;
  863. }
  864. APP.settings.setEmail(email);
  865. APP.UI.setUserAvatar(room.myUserId(), email);
  866. sendEmail(this.commands.defaults.EMAIL, email);
  867. });
  868. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  869. APP.UI.setUserAvatar(data.attributes.id, data.value);
  870. });
  871. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  872. nickname = nickname.trim();
  873. if (nickname === APP.settings.getDisplayName()) {
  874. return;
  875. }
  876. APP.settings.setDisplayName(nickname);
  877. room.setDisplayName(nickname);
  878. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  879. });
  880. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  881. (startAudioMuted, startVideoMuted) => {
  882. room.setStartMutedPolicy({
  883. audio: startAudioMuted,
  884. video: startVideoMuted
  885. });
  886. }
  887. );
  888. room.on(
  889. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  890. ({ audio, video }) => {
  891. APP.UI.onStartMutedChanged(audio, video);
  892. }
  893. );
  894. room.on(ConferenceEvents.STARTED_MUTED, () => {
  895. (room.isStartAudioMuted() || room.isStartVideoMuted())
  896. && APP.UI.notifyInitiallyMuted();
  897. });
  898. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  899. APP.UI.inviteParticipants(
  900. roomUrl,
  901. APP.conference.roomName,
  902. roomLocker.password,
  903. APP.settings.getDisplayName()
  904. );
  905. });
  906. room.on(
  907. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  908. APP.UI.updateDevicesAvailability(id, devices);
  909. }
  910. );
  911. // call hangup
  912. APP.UI.addListener(UIEvents.HANGUP, () => {
  913. hangup(true);
  914. });
  915. // logout
  916. APP.UI.addListener(UIEvents.LOGOUT, () => {
  917. AuthHandler.logout(room).then(function (url) {
  918. if (url) {
  919. window.location.href = url;
  920. } else {
  921. hangup(true);
  922. }
  923. });
  924. });
  925. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  926. room.dial(sipNumber);
  927. });
  928. // Starts or stops the recording for the conference.
  929. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  930. room.toggleRecording(options);
  931. });
  932. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  933. room.setSubject(topic);
  934. });
  935. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  936. APP.UI.setSubject(subject);
  937. });
  938. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  939. room.kickParticipant(id);
  940. });
  941. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  942. room.muteParticipant(id);
  943. });
  944. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  945. AuthHandler.authenticate(room);
  946. });
  947. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  948. room.selectParticipant(id);
  949. });
  950. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  951. var smallVideoId = smallVideo.getId();
  952. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  953. && !APP.conference.isLocalId(smallVideoId))
  954. if (isPinned)
  955. room.pinParticipant(smallVideoId);
  956. // When the library starts supporting multiple pins we would
  957. // pass the isPinned parameter together with the identifier,
  958. // but currently we send null to indicate that we unpin the
  959. // last pinned.
  960. else
  961. room.pinParticipant(null);
  962. });
  963. APP.UI.addListener(
  964. UIEvents.VIDEO_DEVICE_CHANGED,
  965. (cameraDeviceId) => {
  966. APP.settings.setCameraDeviceId(cameraDeviceId);
  967. createLocalTracks('video').then(([stream]) => {
  968. this.useVideoStream(stream);
  969. console.log('switched local video device');
  970. });
  971. }
  972. );
  973. APP.UI.addListener(
  974. UIEvents.AUDIO_DEVICE_CHANGED,
  975. (micDeviceId) => {
  976. APP.settings.setMicDeviceId(micDeviceId);
  977. createLocalTracks('audio').then(([stream]) => {
  978. this.useAudioStream(stream);
  979. console.log('switched local audio device');
  980. });
  981. }
  982. );
  983. APP.UI.addListener(
  984. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  985. );
  986. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  987. (url, state, time, volume) => {
  988. // send start and stop commands once, and remove any updates
  989. // that had left
  990. if (state === 'stop' || state === 'start' || state === 'playing') {
  991. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  992. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  993. value: url,
  994. attributes: {
  995. state: state,
  996. time: time,
  997. volume: volume
  998. }
  999. });
  1000. }
  1001. else {
  1002. // in case of paused, in order to allow late users to join
  1003. // paused
  1004. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1005. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1006. value: url,
  1007. attributes: {
  1008. state: state,
  1009. time: time,
  1010. volume: volume
  1011. }
  1012. });
  1013. }
  1014. });
  1015. room.addCommandListener(
  1016. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1017. if (attributes.state === 'stop') {
  1018. APP.UI.stopSharedVideo(id, attributes);
  1019. } else if (attributes.state === 'start') {
  1020. APP.UI.showSharedVideo(id, value, attributes);
  1021. } else if (attributes.state === 'playing'
  1022. || attributes.state === 'pause') {
  1023. APP.UI.updateSharedVideo(id, value, attributes);
  1024. }
  1025. });
  1026. }
  1027. };