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

conference.js 60KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. import Invite from './modules/UI/invite/Invite';
  4. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  5. import AuthHandler from './modules/UI/authentication/AuthHandler';
  6. import Recorder from './modules/recorder/Recorder';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import {reportError} from './modules/util/helpers';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  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. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  18. let room, connection, localAudio, localVideo;
  19. /**
  20. * Indicates whether extension external installation is in progress or not.
  21. */
  22. let DSExternalInstallationInProgress = false;
  23. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  24. /**
  25. * Known custom conference commands.
  26. */
  27. const commands = {
  28. EMAIL: "email",
  29. AVATAR_URL: "avatar-url",
  30. AVATAR_ID: "avatar-id",
  31. ETHERPAD: "etherpad",
  32. SHARED_VIDEO: "shared-video",
  33. CUSTOM_ROLE: "custom-role"
  34. };
  35. /**
  36. * Open Connection. When authentication failed it shows auth dialog.
  37. * @param roomName the room name to use
  38. * @returns Promise<JitsiConnection>
  39. */
  40. function connect(roomName) {
  41. return openConnection({retry: true, roomName: roomName})
  42. .catch(function (err) {
  43. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  44. APP.UI.notifyTokenAuthFailed();
  45. } else {
  46. APP.UI.notifyConnectionFailed(err);
  47. }
  48. throw err;
  49. });
  50. }
  51. /**
  52. * Creates local media tracks and connects to room. Will show error
  53. * dialogs in case if accessing local microphone and/or camera failed. Will
  54. * show guidance overlay for users on how to give access to camera and/or
  55. * microphone,
  56. * @param {string} roomName
  57. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  58. */
  59. function createInitialLocalTracksAndConnect(roomName) {
  60. let audioAndVideoError,
  61. audioOnlyError;
  62. JitsiMeetJS.mediaDevices.addEventListener(
  63. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  64. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  65. // First try to retrieve both audio and video.
  66. let tryCreateLocalTracks = createLocalTracks(
  67. { devices: ['audio', 'video'] }, true)
  68. .catch(err => {
  69. // If failed then try to retrieve only audio.
  70. audioAndVideoError = err;
  71. return createLocalTracks({ devices: ['audio'] }, true);
  72. })
  73. .catch(err => {
  74. // If audio failed too then just return empty array for tracks.
  75. audioOnlyError = err;
  76. return [];
  77. });
  78. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  79. .then(([tracks, con]) => {
  80. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  81. if (audioAndVideoError) {
  82. if (audioOnlyError) {
  83. // If both requests for 'audio' + 'video' and 'audio' only
  84. // failed, we assume that there is some problems with user's
  85. // microphone and show corresponding dialog.
  86. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  87. } else {
  88. // If request for 'audio' + 'video' failed, but request for
  89. // 'audio' only was OK, we assume that we had problems with
  90. // camera and show corresponding dialog.
  91. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  92. }
  93. }
  94. return [tracks, con];
  95. });
  96. }
  97. /**
  98. * Share data to other users.
  99. * @param command the command
  100. * @param {string} value new value
  101. */
  102. function sendData (command, value) {
  103. room.removeCommand(command);
  104. room.sendCommand(command, {value: value});
  105. }
  106. /**
  107. * Get user nickname by user id.
  108. * @param {string} id user id
  109. * @returns {string?} user nickname or undefined if user is unknown.
  110. */
  111. function getDisplayName (id) {
  112. if (APP.conference.isLocalId(id)) {
  113. return APP.settings.getDisplayName();
  114. }
  115. let participant = room.getParticipantById(id);
  116. if (participant && participant.getDisplayName()) {
  117. return participant.getDisplayName();
  118. }
  119. }
  120. /**
  121. * Mute or unmute local audio stream if it exists.
  122. * @param {boolean} muted - if audio stream should be muted or unmuted.
  123. * @param {boolean} userInteraction - indicates if this local audio mute was a
  124. * result of user interaction
  125. */
  126. function muteLocalAudio (muted) {
  127. muteLocalMedia(localAudio, muted, 'Audio');
  128. }
  129. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  130. if (!localMedia) {
  131. return;
  132. }
  133. const method = muted ? 'mute' : 'unmute';
  134. localMedia[method]().catch(reason => {
  135. console.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  136. });
  137. }
  138. /**
  139. * Mute or unmute local video stream if it exists.
  140. * @param {boolean} muted if video stream should be muted or unmuted.
  141. */
  142. function muteLocalVideo (muted) {
  143. muteLocalMedia(localVideo, muted, 'Video');
  144. }
  145. /**
  146. * Check if the welcome page is enabled and redirects to it.
  147. * If requested show a thank you dialog before that.
  148. * If we have a close page enabled, redirect to it without
  149. * showing any other dialog.
  150. * @param {boolean} showThankYou whether we should show a thank you dialog
  151. */
  152. function maybeRedirectToWelcomePage(showThankYou) {
  153. // if close page is enabled redirect to it, without further action
  154. if (config.enableClosePage) {
  155. window.location.pathname = "close.html";
  156. return;
  157. }
  158. if (showThankYou) {
  159. APP.UI.messageHandler.openMessageDialog(
  160. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  161. }
  162. if (!config.enableWelcomePage) {
  163. return;
  164. }
  165. // redirect to welcome page
  166. setTimeout(() => {
  167. APP.settings.setWelcomePageEnabled(true);
  168. window.location.pathname = "/";
  169. }, 3000);
  170. }
  171. /**
  172. * Create local tracks of specified types.
  173. * @param {Object} options
  174. * @param {string[]} options.devices - required track types
  175. * ('audio', 'video' etc.)
  176. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  177. * undefined - one from settings will be used
  178. * @param {string|null} (options.micDeviceId) - microphone device id, if
  179. * undefined - one from settings will be used
  180. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  181. * for gUM permission prompt
  182. * @returns {Promise<JitsiLocalTrack[]>}
  183. */
  184. function createLocalTracks (options, checkForPermissionPrompt) {
  185. options || (options = {});
  186. return JitsiMeetJS
  187. .createLocalTracks({
  188. // copy array to avoid mutations inside library
  189. devices: options.devices.slice(0),
  190. resolution: config.resolution,
  191. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  192. options.cameraDeviceId === null
  193. ? APP.settings.getCameraDeviceId()
  194. : options.cameraDeviceId,
  195. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  196. options.micDeviceId === null
  197. ? APP.settings.getMicDeviceId()
  198. : options.micDeviceId,
  199. // adds any ff fake device settings if any
  200. firefox_fake_device: config.firefox_fake_device,
  201. desktopSharingExtensionExternalInstallation:
  202. options.desktopSharingExtensionExternalInstallation
  203. }, checkForPermissionPrompt).then( (tracks) => {
  204. tracks.forEach((track) => {
  205. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  206. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  207. });
  208. return tracks;
  209. }).catch(function (err) {
  210. console.error(
  211. 'failed to create local tracks', options.devices, err);
  212. return Promise.reject(err);
  213. });
  214. }
  215. /**
  216. * Changes the email for the local user
  217. * @param email {string} the new email
  218. */
  219. function changeLocalEmail(email = '') {
  220. email = email.trim();
  221. if (email === APP.settings.getEmail()) {
  222. return;
  223. }
  224. APP.settings.setEmail(email);
  225. APP.UI.setUserEmail(room.myUserId(), email);
  226. sendData(commands.EMAIL, email);
  227. }
  228. /**
  229. * Changes the display name for the local user
  230. * @param nickname {string} the new display name
  231. */
  232. function changeLocalDisplayName(nickname = '') {
  233. nickname = nickname.trim();
  234. if (nickname === APP.settings.getDisplayName()) {
  235. return;
  236. }
  237. APP.settings.setDisplayName(nickname);
  238. room.setDisplayName(nickname);
  239. APP.UI.changeDisplayName(APP.conference.getMyUserId(), nickname);
  240. }
  241. class ConferenceConnector {
  242. constructor(resolve, reject) {
  243. this._resolve = resolve;
  244. this._reject = reject;
  245. this.reconnectTimeout = null;
  246. room.on(ConferenceEvents.CONFERENCE_JOINED,
  247. this._handleConferenceJoined.bind(this));
  248. room.on(ConferenceEvents.CONFERENCE_FAILED,
  249. this._onConferenceFailed.bind(this));
  250. room.on(ConferenceEvents.CONFERENCE_ERROR,
  251. this._onConferenceError.bind(this));
  252. }
  253. _handleConferenceFailed(err) {
  254. this._unsubscribe();
  255. this._reject(err);
  256. }
  257. _onConferenceFailed(err, ...params) {
  258. console.error('CONFERENCE FAILED:', err, ...params);
  259. APP.UI.hideRingOverLay();
  260. switch (err) {
  261. // room is locked by the password
  262. case ConferenceErrors.PASSWORD_REQUIRED:
  263. APP.UI.emitEvent(UIEvents.PASSWORD_REQUIRED);
  264. break;
  265. case ConferenceErrors.CONNECTION_ERROR:
  266. {
  267. let [msg] = params;
  268. APP.UI.notifyConnectionFailed(msg);
  269. }
  270. break;
  271. case ConferenceErrors.NOT_ALLOWED_ERROR:
  272. {
  273. // let's show some auth not allowed page
  274. window.location.pathname = "authError.html";
  275. }
  276. break;
  277. // not enough rights to create conference
  278. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  279. // schedule reconnect to check if someone else created the room
  280. this.reconnectTimeout = setTimeout(function () {
  281. room.join();
  282. }, 5000);
  283. // notify user that auth is required
  284. AuthHandler.requireAuth(room, this.invite.getRoomLocker().password);
  285. break;
  286. case ConferenceErrors.RESERVATION_ERROR:
  287. {
  288. let [code, msg] = params;
  289. APP.UI.notifyReservationError(code, msg);
  290. }
  291. break;
  292. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  293. APP.UI.notifyGracefulShutdown();
  294. break;
  295. case ConferenceErrors.JINGLE_FATAL_ERROR:
  296. APP.UI.notifyInternalError();
  297. break;
  298. case ConferenceErrors.CONFERENCE_DESTROYED:
  299. {
  300. let [reason] = params;
  301. APP.UI.hideStats();
  302. APP.UI.notifyConferenceDestroyed(reason);
  303. }
  304. break;
  305. // FIXME FOCUS_DISCONNECTED is confusing event name.
  306. // What really happens there is that the library is not ready yet,
  307. // because Jicofo is not available, but it is going to give
  308. // it another try.
  309. case ConferenceErrors.FOCUS_DISCONNECTED:
  310. {
  311. let [focus, retrySec] = params;
  312. APP.UI.notifyFocusDisconnected(focus, retrySec);
  313. }
  314. break;
  315. case ConferenceErrors.FOCUS_LEFT:
  316. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  317. // Log the page reload event
  318. // FIXME (CallStats - issue) this event will not make it to
  319. // the CallStats, because the log queue is not flushed, before
  320. // "fabric terminated" is sent to the backed
  321. APP.conference.logEvent('page.reload');
  322. // FIXME the conference should be stopped by the library and not by
  323. // the app. Both the errors above are unrecoverable from the library
  324. // perspective.
  325. room.leave().then(() => connection.disconnect());
  326. APP.UI.showPageReloadOverlay();
  327. break;
  328. case ConferenceErrors.CONFERENCE_MAX_USERS:
  329. connection.disconnect();
  330. APP.UI.notifyMaxUsersLimitReached();
  331. break;
  332. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  333. window.location.reload();
  334. break;
  335. default:
  336. this._handleConferenceFailed(err, ...params);
  337. }
  338. }
  339. _onConferenceError(err, ...params) {
  340. console.error('CONFERENCE Error:', err, params);
  341. switch (err) {
  342. case ConferenceErrors.CHAT_ERROR:
  343. {
  344. let [code, msg] = params;
  345. APP.UI.showChatError(code, msg);
  346. }
  347. break;
  348. default:
  349. console.error("Unknown error.");
  350. }
  351. }
  352. _unsubscribe() {
  353. room.off(
  354. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  355. room.off(
  356. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  357. if (this.reconnectTimeout !== null) {
  358. clearTimeout(this.reconnectTimeout);
  359. }
  360. AuthHandler.closeAuth();
  361. }
  362. _handleConferenceJoined() {
  363. this._unsubscribe();
  364. this._resolve();
  365. }
  366. connect() {
  367. room.join();
  368. }
  369. }
  370. /**
  371. * Disconnects the connection.
  372. * @returns resolved Promise. We need this in order to make the Promise.all
  373. * call in hangup() to resolve when all operations are finished.
  374. */
  375. function disconnect() {
  376. connection.disconnect();
  377. APP.API.notifyConferenceLeft(APP.conference.roomName);
  378. return Promise.resolve();
  379. }
  380. /**
  381. * Set permanent ptoperties to analytics.
  382. * NOTE: Has to be used after JitsiMeetJS.init. otherwise analytics will be
  383. * null.
  384. */
  385. function setAnalyticsPermanentProperties() {
  386. let permanentProperties = {
  387. userAgent: navigator.userAgent,
  388. roomName: APP.conference.roomName
  389. };
  390. let {server, group} = APP.tokenData;
  391. if(server) {
  392. permanentProperties.server = server;
  393. }
  394. if(group) {
  395. permanentProperties.group = group;
  396. }
  397. JitsiMeetJS.analytics.addPermanentProperties(permanentProperties);
  398. }
  399. export default {
  400. isModerator: false,
  401. audioMuted: false,
  402. videoMuted: false,
  403. isSharingScreen: false,
  404. isDesktopSharingEnabled: false,
  405. /*
  406. * Whether the local "raisedHand" flag is on.
  407. */
  408. isHandRaised: false,
  409. /*
  410. * Whether the local participant is the dominant speaker in the conference.
  411. */
  412. isDominantSpeaker: false,
  413. /**
  414. * Open new connection and join to the conference.
  415. * @param {object} options
  416. * @param {string} roomName name of the conference
  417. * @returns {Promise}
  418. */
  419. init(options) {
  420. this.roomName = options.roomName;
  421. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  422. // attaches global error handler, if there is already one, respect it
  423. if(JitsiMeetJS.getGlobalOnErrorHandler){
  424. var oldOnErrorHandler = window.onerror;
  425. window.onerror = function (message, source, lineno, colno, error) {
  426. JitsiMeetJS.getGlobalOnErrorHandler(
  427. message, source, lineno, colno, error);
  428. if(oldOnErrorHandler)
  429. oldOnErrorHandler(message, source, lineno, colno, error);
  430. };
  431. var oldOnUnhandledRejection = window.onunhandledrejection;
  432. window.onunhandledrejection = function(event) {
  433. JitsiMeetJS.getGlobalOnErrorHandler(
  434. null, null, null, null, event.reason);
  435. if(oldOnUnhandledRejection)
  436. oldOnUnhandledRejection(event);
  437. };
  438. }
  439. return JitsiMeetJS.init(config)
  440. .then(() => {
  441. setAnalyticsPermanentProperties();
  442. return createInitialLocalTracksAndConnect(options.roomName);
  443. }).then(([tracks, con]) => {
  444. console.log('initialized with %s local tracks', tracks.length);
  445. APP.connection = connection = con;
  446. this._bindConnectionFailedHandler(con);
  447. this._createRoom(tracks);
  448. this.isDesktopSharingEnabled =
  449. JitsiMeetJS.isDesktopSharingEnabled();
  450. APP.UI.ContactList = new ContactList(room);
  451. // if user didn't give access to mic or camera or doesn't have
  452. // them at all, we disable corresponding toolbar buttons
  453. if (!tracks.find((t) => t.isAudioTrack())) {
  454. APP.UI.setMicrophoneButtonEnabled(false);
  455. }
  456. if (!tracks.find((t) => t.isVideoTrack())) {
  457. APP.UI.setCameraButtonEnabled(false);
  458. }
  459. this._initDeviceList();
  460. if (config.iAmRecorder)
  461. this.recorder = new Recorder();
  462. // XXX The API will take care of disconnecting from the XMPP
  463. // server (and, thus, leaving the room) on unload.
  464. return new Promise((resolve, reject) => {
  465. (new ConferenceConnector(resolve, reject)).connect();
  466. });
  467. });
  468. },
  469. /**
  470. * Check if id is id of the local user.
  471. * @param {string} id id to check
  472. * @returns {boolean}
  473. */
  474. isLocalId (id) {
  475. return this.getMyUserId() === id;
  476. },
  477. /**
  478. * Binds a handler that will handle the case when the connection is dropped
  479. * in the middle of the conference.
  480. * @param {JitsiConnection} connection the connection to which the handler
  481. * will be bound to.
  482. * @private
  483. */
  484. _bindConnectionFailedHandler (connection) {
  485. const handler = function (error, errMsg) {
  486. if (ConnectionErrors.OTHER_ERROR === error) {
  487. // - item-not-found
  488. // - connection dropped(closed by Strophe unexpectedly
  489. // possible due too many transport errors)
  490. console.error("XMPP connection error: " + errMsg);
  491. APP.UI.showPageReloadOverlay();
  492. connection.removeEventListener(
  493. ConnectionEvents.CONNECTION_FAILED, handler);
  494. }
  495. };
  496. connection.addEventListener(
  497. ConnectionEvents.CONNECTION_FAILED, handler);
  498. },
  499. /**
  500. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  501. * @param mute true for mute and false for unmute.
  502. */
  503. muteAudio (mute) {
  504. muteLocalAudio(mute);
  505. },
  506. /**
  507. * Returns whether local audio is muted or not.
  508. * @returns {boolean}
  509. */
  510. isLocalAudioMuted() {
  511. return this.audioMuted;
  512. },
  513. /**
  514. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  515. */
  516. toggleAudioMuted () {
  517. this.muteAudio(!this.audioMuted);
  518. },
  519. /**
  520. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  521. * @param mute true for mute and false for unmute.
  522. */
  523. muteVideo (mute) {
  524. muteLocalVideo(mute);
  525. },
  526. /**
  527. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  528. */
  529. toggleVideoMuted () {
  530. this.muteVideo(!this.videoMuted);
  531. },
  532. /**
  533. * Retrieve list of conference participants (without local user).
  534. * @returns {JitsiParticipant[]}
  535. */
  536. listMembers () {
  537. return room.getParticipants();
  538. },
  539. /**
  540. * Retrieve list of ids of conference participants (without local user).
  541. * @returns {string[]}
  542. */
  543. listMembersIds () {
  544. return room.getParticipants().map(p => p.getId());
  545. },
  546. /**
  547. * Checks whether the participant identified by id is a moderator.
  548. * @id id to search for participant
  549. * @return {boolean} whether the participant is moderator
  550. */
  551. isParticipantModerator (id) {
  552. let user = room.getParticipantById(id);
  553. return user && user.isModerator();
  554. },
  555. /**
  556. * Check if SIP is supported.
  557. * @returns {boolean}
  558. */
  559. sipGatewayEnabled () {
  560. return room.isSIPCallingSupported();
  561. },
  562. get membersCount () {
  563. return room.getParticipants().length + 1;
  564. },
  565. /**
  566. * Returns true if the callstats integration is enabled, otherwise returns
  567. * false.
  568. *
  569. * @returns true if the callstats integration is enabled, otherwise returns
  570. * false.
  571. */
  572. isCallstatsEnabled () {
  573. return room.isCallstatsEnabled();
  574. },
  575. /**
  576. * Sends the given feedback through CallStats if enabled.
  577. *
  578. * @param overallFeedback an integer between 1 and 5 indicating the
  579. * user feedback
  580. * @param detailedFeedback detailed feedback from the user. Not yet used
  581. */
  582. sendFeedback (overallFeedback, detailedFeedback) {
  583. return room.sendFeedback (overallFeedback, detailedFeedback);
  584. },
  585. /**
  586. * Returns the connection times stored in the library.
  587. */
  588. getConnectionTimes () {
  589. return this._room.getConnectionTimes();
  590. },
  591. // used by torture currently
  592. isJoined () {
  593. return this._room
  594. && this._room.isJoined();
  595. },
  596. getConnectionState () {
  597. return this._room
  598. && this._room.getConnectionState();
  599. },
  600. /**
  601. * Checks whether or not our connection is currently in interrupted and
  602. * reconnect attempts are in progress.
  603. *
  604. * @returns {boolean} true if the connection is in interrupted state or
  605. * false otherwise.
  606. */
  607. isConnectionInterrupted () {
  608. return this._room.isConnectionInterrupted();
  609. },
  610. /**
  611. * Finds JitsiParticipant for given id.
  612. *
  613. * @param {string} id participant's identifier(MUC nickname).
  614. *
  615. * @returns {JitsiParticipant|null} participant instance for given id or
  616. * null if not found.
  617. */
  618. getParticipantById (id) {
  619. return room ? room.getParticipantById(id) : null;
  620. },
  621. /**
  622. * Checks whether the user identified by given id is currently connected.
  623. *
  624. * @param {string} id participant's identifier(MUC nickname)
  625. *
  626. * @returns {boolean|null} true if participant's connection is ok or false
  627. * if the user is having connectivity issues.
  628. */
  629. isParticipantConnectionActive (id) {
  630. let participant = this.getParticipantById(id);
  631. return participant ? participant.isConnectionActive() : null;
  632. },
  633. /**
  634. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  635. * the given <tt>id</tt>.
  636. *
  637. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  638. *
  639. * @return {string} the participant's display name or the default string if
  640. * absent.
  641. */
  642. getParticipantDisplayName (id) {
  643. let displayName = getDisplayName(id);
  644. if (displayName) {
  645. return displayName;
  646. } else {
  647. if (APP.conference.isLocalId(id)) {
  648. return APP.translation.generateTranslationHTML(
  649. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  650. } else {
  651. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  652. }
  653. }
  654. },
  655. getMyUserId () {
  656. return this._room
  657. && this._room.myUserId();
  658. },
  659. /**
  660. * Indicates if recording is supported in this conference.
  661. */
  662. isRecordingSupported() {
  663. return this._room && this._room.isRecordingSupported();
  664. },
  665. /**
  666. * Returns the recording state or undefined if the room is not defined.
  667. */
  668. getRecordingState() {
  669. return (this._room) ? this._room.getRecordingState() : undefined;
  670. },
  671. /**
  672. * Will be filled with values only when config.debug is enabled.
  673. * Its used by torture to check audio levels.
  674. */
  675. audioLevelsMap: {},
  676. /**
  677. * Returns the stored audio level (stored only if config.debug is enabled)
  678. * @param id the id for the user audio level to return (the id value is
  679. * returned for the participant using getMyUserId() method)
  680. */
  681. getPeerSSRCAudioLevel (id) {
  682. return this.audioLevelsMap[id];
  683. },
  684. /**
  685. * @return {number} the number of participants in the conference with at
  686. * least one track.
  687. */
  688. getNumberOfParticipantsWithTracks() {
  689. return this._room.getParticipants()
  690. .filter((p) => p.getTracks().length > 0)
  691. .length;
  692. },
  693. /**
  694. * Returns the stats.
  695. */
  696. getStats() {
  697. return room.connectionQuality.getStats();
  698. },
  699. // end used by torture
  700. getLogs () {
  701. return room.getLogs();
  702. },
  703. /**
  704. * Download logs, a function that can be called from console while
  705. * debugging.
  706. * @param filename (optional) specify target filename
  707. */
  708. saveLogs (filename = 'meetlog.json') {
  709. // this can be called from console and will not have reference to this
  710. // that's why we reference the global var
  711. let logs = APP.conference.getLogs();
  712. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  713. let elem = document.createElement('a');
  714. elem.download = filename;
  715. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  716. elem.dataset.downloadurl
  717. = ['text/json', elem.download, elem.href].join(':');
  718. elem.dispatchEvent(new MouseEvent('click', {
  719. view: window,
  720. bubbles: true,
  721. cancelable: false
  722. }));
  723. },
  724. /**
  725. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  726. * desire to keep room private to this instance and (2) the need of other
  727. * modules to send and receive commands to and from participants.
  728. * Eventually, this instance remains in control with respect to the
  729. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  730. * JitsiConference) is to be used in the implementation of the Command(s)
  731. * API of this instance.
  732. */
  733. commands: {
  734. /**
  735. * Known custom conference commands.
  736. */
  737. defaults: commands,
  738. /**
  739. * Receives notifications from other participants about commands aka
  740. * custom events (sent by sendCommand or sendCommandOnce methods).
  741. * @param command {String} the name of the command
  742. * @param handler {Function} handler for the command
  743. */
  744. addCommandListener () {
  745. room.addCommandListener.apply(room, arguments);
  746. },
  747. /**
  748. * Removes command.
  749. * @param name {String} the name of the command.
  750. */
  751. removeCommand () {
  752. room.removeCommand.apply(room, arguments);
  753. },
  754. /**
  755. * Sends command.
  756. * @param name {String} the name of the command.
  757. * @param values {Object} with keys and values that will be sent.
  758. */
  759. sendCommand () {
  760. room.sendCommand.apply(room, arguments);
  761. },
  762. /**
  763. * Sends command one time.
  764. * @param name {String} the name of the command.
  765. * @param values {Object} with keys and values that will be sent.
  766. */
  767. sendCommandOnce () {
  768. room.sendCommandOnce.apply(room, arguments);
  769. }
  770. },
  771. _createRoom (localTracks) {
  772. room = connection.initJitsiConference(APP.conference.roomName,
  773. this._getConferenceOptions());
  774. this._setLocalAudioVideoStreams(localTracks);
  775. this.invite = new Invite(room);
  776. this._room = room; // FIXME do not use this
  777. let email = APP.settings.getEmail();
  778. email && sendData(this.commands.defaults.EMAIL, email);
  779. let avatarUrl = APP.settings.getAvatarUrl();
  780. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  781. avatarUrl);
  782. !email && sendData(
  783. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  784. let nick = APP.settings.getDisplayName();
  785. if (config.useNicks && !nick) {
  786. nick = APP.UI.askForNickname();
  787. APP.settings.setDisplayName(nick);
  788. }
  789. nick && room.setDisplayName(nick);
  790. this._setupListeners();
  791. },
  792. /**
  793. * Sets local video and audio streams.
  794. * @param {JitsiLocalTrack[]} tracks=[]
  795. * @returns {Promise[]}
  796. * @private
  797. */
  798. _setLocalAudioVideoStreams(tracks = []) {
  799. return tracks.map(track => {
  800. if (track.isAudioTrack()) {
  801. return this.useAudioStream(track);
  802. } else if (track.isVideoTrack()) {
  803. return this.useVideoStream(track);
  804. } else {
  805. console.error(
  806. "Ignored not an audio nor a video track: ", track);
  807. return Promise.resolve();
  808. }
  809. });
  810. },
  811. _getConferenceOptions() {
  812. let options = config;
  813. if(config.enableRecording && !config.recordingType) {
  814. options.recordingType = (config.hosts &&
  815. (typeof config.hosts.jirecon != "undefined"))?
  816. "jirecon" : "colibri";
  817. }
  818. return options;
  819. },
  820. /**
  821. * Start using provided video stream.
  822. * Stops previous video stream.
  823. * @param {JitsiLocalTrack} [stream] new stream to use or null
  824. * @returns {Promise}
  825. */
  826. useVideoStream (stream) {
  827. let promise = Promise.resolve();
  828. if (localVideo) {
  829. // this calls room.removeTrack internally
  830. // so we don't need to remove it manually
  831. promise = localVideo.dispose();
  832. }
  833. localVideo = stream;
  834. return promise.then(function () {
  835. if (stream) {
  836. return room.addTrack(stream);
  837. }
  838. }).then(() => {
  839. if (stream) {
  840. this.videoMuted = stream.isMuted();
  841. this.isSharingScreen = stream.videoType === 'desktop';
  842. APP.UI.addLocalStream(stream);
  843. stream.videoType === 'camera'
  844. && APP.UI.setCameraButtonEnabled(true);
  845. } else {
  846. this.videoMuted = false;
  847. this.isSharingScreen = false;
  848. }
  849. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  850. APP.UI.updateDesktopSharingButtons();
  851. });
  852. },
  853. /**
  854. * Start using provided audio stream.
  855. * Stops previous audio stream.
  856. * @param {JitsiLocalTrack} [stream] new stream to use or null
  857. * @returns {Promise}
  858. */
  859. useAudioStream (stream) {
  860. let promise = Promise.resolve();
  861. if (localAudio) {
  862. // this calls room.removeTrack internally
  863. // so we don't need to remove it manually
  864. promise = localAudio.dispose();
  865. }
  866. localAudio = stream;
  867. return promise.then(function () {
  868. if (stream) {
  869. return room.addTrack(stream);
  870. }
  871. }).then(() => {
  872. if (stream) {
  873. this.audioMuted = stream.isMuted();
  874. APP.UI.addLocalStream(stream);
  875. } else {
  876. this.audioMuted = false;
  877. }
  878. APP.UI.setMicrophoneButtonEnabled(true);
  879. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  880. });
  881. },
  882. videoSwitchInProgress: false,
  883. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  884. if (this.videoSwitchInProgress) {
  885. console.warn("Switch in progress.");
  886. return;
  887. }
  888. if (!this.isDesktopSharingEnabled) {
  889. console.warn("Cannot toggle screen sharing: not supported.");
  890. return;
  891. }
  892. this.videoSwitchInProgress = true;
  893. let externalInstallation = false;
  894. if (shareScreen) {
  895. createLocalTracks({
  896. devices: ['desktop'],
  897. desktopSharingExtensionExternalInstallation: {
  898. interval: 500,
  899. checkAgain: () => {
  900. return DSExternalInstallationInProgress;
  901. },
  902. listener: (status, url) => {
  903. switch(status) {
  904. case "waitingForExtension":
  905. DSExternalInstallationInProgress = true;
  906. externalInstallation = true;
  907. APP.UI.showExtensionExternalInstallationDialog(
  908. url);
  909. break;
  910. case "extensionFound":
  911. if(externalInstallation) //close the dialog
  912. $.prompt.close();
  913. break;
  914. default:
  915. //Unknown status
  916. }
  917. }
  918. }
  919. }).then(([stream]) => {
  920. DSExternalInstallationInProgress = false;
  921. // close external installation dialog on success.
  922. if(externalInstallation)
  923. $.prompt.close();
  924. stream.on(
  925. TrackEvents.LOCAL_TRACK_STOPPED,
  926. () => {
  927. // if stream was stopped during screensharing session
  928. // then we should switch to video
  929. // otherwise we stopped it because we already switched
  930. // to video, so nothing to do here
  931. if (this.isSharingScreen) {
  932. this.toggleScreenSharing(false);
  933. }
  934. }
  935. );
  936. return this.useVideoStream(stream);
  937. }).then(() => {
  938. this.videoSwitchInProgress = false;
  939. JitsiMeetJS.analytics.sendEvent(
  940. 'conference.sharingDesktop.start');
  941. console.log('sharing local desktop');
  942. }).catch((err) => {
  943. // close external installation dialog to show the error.
  944. if(externalInstallation)
  945. $.prompt.close();
  946. this.videoSwitchInProgress = false;
  947. this.toggleScreenSharing(false);
  948. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  949. return;
  950. }
  951. console.error('failed to share local desktop', err);
  952. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  953. APP.UI.showExtensionRequiredDialog(
  954. config.desktopSharingFirefoxExtensionURL
  955. );
  956. return;
  957. }
  958. // Handling:
  959. // TrackErrors.PERMISSION_DENIED
  960. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  961. // TrackErrors.GENERAL
  962. // and any other
  963. let dialogTxt;
  964. let dialogTitleKey;
  965. if (err.name === TrackErrors.PERMISSION_DENIED) {
  966. dialogTxt = APP.translation.generateTranslationHTML(
  967. "dialog.screenSharingPermissionDeniedError");
  968. dialogTitleKey = "dialog.error";
  969. } else {
  970. dialogTxt = APP.translation.generateTranslationHTML(
  971. "dialog.failtoinstall");
  972. dialogTitleKey = "dialog.permissionDenied";
  973. }
  974. APP.UI.messageHandler.openDialog(
  975. dialogTitleKey, dialogTxt, false);
  976. });
  977. } else {
  978. createLocalTracks({ devices: ['video'] }).then(
  979. ([stream]) => this.useVideoStream(stream)
  980. ).then(() => {
  981. this.videoSwitchInProgress = false;
  982. JitsiMeetJS.analytics.sendEvent(
  983. 'conference.sharingDesktop.stop');
  984. console.log('sharing local video');
  985. }).catch((err) => {
  986. this.useVideoStream(null);
  987. this.videoSwitchInProgress = false;
  988. console.error('failed to share local video', err);
  989. });
  990. }
  991. },
  992. /**
  993. * Setup interaction between conference and UI.
  994. */
  995. _setupListeners () {
  996. // add local streams when joined to the conference
  997. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  998. APP.UI.mucJoined();
  999. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1000. APP.UI.markVideoInterrupted(false);
  1001. });
  1002. room.on(
  1003. ConferenceEvents.AUTH_STATUS_CHANGED,
  1004. function (authEnabled, authLogin) {
  1005. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1006. }
  1007. );
  1008. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1009. if (user.isHidden())
  1010. return;
  1011. console.log('USER %s connnected', id, user);
  1012. APP.API.notifyUserJoined(id);
  1013. APP.UI.addUser(user);
  1014. // check the roles for the new user and reflect them
  1015. APP.UI.updateUserRole(user);
  1016. });
  1017. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1018. console.log('USER %s LEFT', id, user);
  1019. APP.API.notifyUserLeft(id);
  1020. APP.UI.removeUser(id, user.getDisplayName());
  1021. APP.UI.onSharedVideoStop(id);
  1022. });
  1023. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1024. if (this.isLocalId(id)) {
  1025. console.info(`My role changed, new role: ${role}`);
  1026. if (this.isModerator !== room.isModerator()) {
  1027. this.isModerator = room.isModerator();
  1028. APP.UI.updateLocalRole(room.isModerator());
  1029. }
  1030. } else {
  1031. let user = room.getParticipantById(id);
  1032. if (user) {
  1033. APP.UI.updateUserRole(user);
  1034. }
  1035. }
  1036. });
  1037. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1038. if(!track || track.isLocal())
  1039. return;
  1040. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1041. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1042. });
  1043. APP.UI.addRemoteStream(track);
  1044. });
  1045. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1046. if(!track || track.isLocal())
  1047. return;
  1048. APP.UI.removeRemoteStream(track);
  1049. });
  1050. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1051. if(!track)
  1052. return;
  1053. const handler = (track.getType() === "audio")?
  1054. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1055. let id;
  1056. const mute = track.isMuted();
  1057. if(track.isLocal()){
  1058. id = APP.conference.getMyUserId();
  1059. if(track.getType() === "audio") {
  1060. this.audioMuted = mute;
  1061. } else {
  1062. this.videoMuted = mute;
  1063. }
  1064. } else {
  1065. id = track.getParticipantId();
  1066. }
  1067. handler(id , mute);
  1068. });
  1069. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1070. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1071. lvl = 0;
  1072. }
  1073. if(config.debug)
  1074. {
  1075. this.audioLevelsMap[id] = lvl;
  1076. if(config.debugAudioLevels)
  1077. console.log("AudioLevel:" + id + "/" + lvl);
  1078. }
  1079. APP.UI.setAudioLevel(id, lvl);
  1080. });
  1081. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1082. APP.UI.showToolbar(6000);
  1083. UIUtil.animateShowElement($("#talkWhileMutedPopup"), true, 5000);
  1084. });
  1085. /*
  1086. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1087. //FIXME
  1088. if (config.muteLocalVideoIfNotInLastN) {
  1089. // TODO mute or unmute if required
  1090. // mark video on UI
  1091. // APP.UI.markVideoMuted(true/false);
  1092. }
  1093. });
  1094. */
  1095. room.on(
  1096. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1097. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1098. });
  1099. room.on(
  1100. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1101. (id, isActive) => {
  1102. APP.UI.participantConnectionStatusChanged(id, isActive);
  1103. });
  1104. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1105. if (this.isLocalId(id)) {
  1106. this.isDominantSpeaker = true;
  1107. this.setRaisedHand(false);
  1108. } else {
  1109. this.isDominantSpeaker = false;
  1110. var participant = room.getParticipantById(id);
  1111. if (participant) {
  1112. APP.UI.setRaisedHandStatus(participant, false);
  1113. }
  1114. }
  1115. APP.UI.markDominantSpeaker(id);
  1116. });
  1117. if (!interfaceConfig.filmStripOnly) {
  1118. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1119. APP.UI.markVideoInterrupted(true);
  1120. });
  1121. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1122. APP.UI.markVideoInterrupted(false);
  1123. });
  1124. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1125. let nick = getDisplayName(id);
  1126. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1127. APP.UI.addMessage(id, nick, text, ts);
  1128. });
  1129. }
  1130. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1131. APP.UI.showLocalConnectionInterrupted(true);
  1132. });
  1133. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1134. APP.UI.showLocalConnectionInterrupted(false);
  1135. });
  1136. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1137. APP.API.notifyDisplayNameChanged(id, displayName);
  1138. APP.UI.changeDisplayName(id, displayName);
  1139. });
  1140. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1141. (participant, name, oldValue, newValue) => {
  1142. if (name === "raisedHand") {
  1143. APP.UI.setRaisedHandStatus(participant, newValue);
  1144. }
  1145. });
  1146. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1147. console.log("Received recorder status change: ", status, error);
  1148. APP.UI.updateRecordingState(status);
  1149. });
  1150. room.on(ConferenceEvents.KICKED, () => {
  1151. APP.UI.hideStats();
  1152. APP.UI.notifyKicked();
  1153. // FIXME close
  1154. });
  1155. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1156. APP.UI.updateDTMFSupport(isDTMFSupported);
  1157. });
  1158. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1159. // Wait a little bit more just to be sure that we won't miss the
  1160. // extension installation
  1161. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1162. });
  1163. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1164. window.open(
  1165. url, "extension_store_window",
  1166. "resizable,scrollbars=yes,status=1");
  1167. });
  1168. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1169. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1170. if (!interfaceConfig.filmStripOnly) {
  1171. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1172. APP.API.notifySendingChatMessage(message);
  1173. room.sendTextMessage(message);
  1174. });
  1175. }
  1176. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1177. (stats) => {
  1178. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1179. });
  1180. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1181. (id, percent, stats) => {
  1182. APP.UI.updateRemoteStats(id, percent, stats);
  1183. });
  1184. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1185. APP.UI.initEtherpad(value);
  1186. });
  1187. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1188. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1189. APP.UI.setUserEmail(from, data.value);
  1190. });
  1191. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1192. (data, from) => {
  1193. APP.UI.setUserAvatarUrl(from, data.value);
  1194. });
  1195. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1196. (data, from) => {
  1197. APP.UI.setUserAvatarID(from, data.value);
  1198. });
  1199. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1200. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1201. (startAudioMuted, startVideoMuted) => {
  1202. room.setStartMutedPolicy({
  1203. audio: startAudioMuted,
  1204. video: startVideoMuted
  1205. });
  1206. }
  1207. );
  1208. room.on(
  1209. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1210. ({ audio, video }) => {
  1211. APP.UI.onStartMutedChanged(audio, video);
  1212. }
  1213. );
  1214. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1215. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1216. && APP.UI.notifyInitiallyMuted();
  1217. });
  1218. room.on(
  1219. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1220. APP.UI.updateDevicesAvailability(id, devices);
  1221. }
  1222. );
  1223. // call hangup
  1224. APP.UI.addListener(UIEvents.HANGUP, () => {
  1225. this.hangup(true);
  1226. });
  1227. // logout
  1228. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1229. AuthHandler.logout(room).then(url => {
  1230. if (url) {
  1231. window.location.href = url;
  1232. } else {
  1233. this.hangup(true);
  1234. }
  1235. });
  1236. });
  1237. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1238. room.dial(sipNumber);
  1239. });
  1240. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1241. (id, oldResolution, newResolution, delay) => {
  1242. var logObject = {
  1243. id: "resolution_change",
  1244. participant: id,
  1245. oldValue: oldResolution,
  1246. newValue: newResolution,
  1247. delay: delay
  1248. };
  1249. room.sendApplicationLog(JSON.stringify(logObject));
  1250. // We only care about the delay between simulcast streams.
  1251. // Longer delays will be caused by something else and will just
  1252. // poison the data.
  1253. if (delay < 2000) {
  1254. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1255. {value: delay});
  1256. }
  1257. });
  1258. // Starts or stops the recording for the conference.
  1259. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1260. room.toggleRecording(options);
  1261. });
  1262. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1263. room.setSubject(topic);
  1264. });
  1265. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1266. APP.UI.setSubject(subject);
  1267. });
  1268. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1269. room.kickParticipant(id);
  1270. });
  1271. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1272. room.muteParticipant(id);
  1273. });
  1274. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1275. AuthHandler.authenticate(room);
  1276. });
  1277. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1278. try {
  1279. // do not try to select participant if there is none (we are
  1280. // alone in the room), otherwise an error will be thrown cause
  1281. // reporting mechanism is not available (datachannels currently)
  1282. if (room.getParticipants().length === 0)
  1283. return;
  1284. room.selectParticipant(id);
  1285. } catch (e) {
  1286. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1287. reportError(e);
  1288. }
  1289. });
  1290. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1291. var smallVideoId = smallVideo.getId();
  1292. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1293. // the participant is on the large video ?
  1294. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1295. && !APP.conference.isLocalId(smallVideoId)) {
  1296. // When the library starts supporting multiple pins we would
  1297. // pass the isPinned parameter together with the identifier,
  1298. // but currently we send null to indicate that we unpin the
  1299. // last pinned.
  1300. try {
  1301. room.pinParticipant(isPinned ? smallVideoId : null);
  1302. } catch (e) {
  1303. reportError(e);
  1304. }
  1305. }
  1306. });
  1307. APP.UI.addListener(
  1308. UIEvents.VIDEO_DEVICE_CHANGED,
  1309. (cameraDeviceId) => {
  1310. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1311. createLocalTracks({
  1312. devices: ['video'],
  1313. cameraDeviceId: cameraDeviceId,
  1314. micDeviceId: null
  1315. })
  1316. .then(([stream]) => {
  1317. this.useVideoStream(stream);
  1318. console.log('switched local video device');
  1319. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1320. })
  1321. .catch((err) => {
  1322. APP.UI.showDeviceErrorDialog(null, err);
  1323. APP.UI.setSelectedCameraFromSettings();
  1324. });
  1325. }
  1326. );
  1327. APP.UI.addListener(
  1328. UIEvents.AUDIO_DEVICE_CHANGED,
  1329. (micDeviceId) => {
  1330. JitsiMeetJS.analytics.sendEvent(
  1331. 'settings.changeDevice.audioIn');
  1332. createLocalTracks({
  1333. devices: ['audio'],
  1334. cameraDeviceId: null,
  1335. micDeviceId: micDeviceId
  1336. })
  1337. .then(([stream]) => {
  1338. this.useAudioStream(stream);
  1339. console.log('switched local audio device');
  1340. APP.settings.setMicDeviceId(micDeviceId, true);
  1341. })
  1342. .catch((err) => {
  1343. APP.UI.showDeviceErrorDialog(err, null);
  1344. APP.UI.setSelectedMicFromSettings();
  1345. });
  1346. }
  1347. );
  1348. APP.UI.addListener(
  1349. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1350. (audioOutputDeviceId) => {
  1351. JitsiMeetJS.analytics.sendEvent(
  1352. 'settings.changeDevice.audioOut');
  1353. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1354. .then(() => console.log('changed audio output device'))
  1355. .catch((err) => {
  1356. console.warn('Failed to change audio output device. ' +
  1357. 'Default or previously set audio output device ' +
  1358. 'will be used instead.', err);
  1359. APP.UI.setSelectedAudioOutputFromSettings();
  1360. });
  1361. }
  1362. );
  1363. APP.UI.addListener(
  1364. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1365. );
  1366. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1367. (url, state, time, isMuted, volume) => {
  1368. // send start and stop commands once, and remove any updates
  1369. // that had left
  1370. if (state === 'stop' || state === 'start' || state === 'playing') {
  1371. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1372. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1373. value: url,
  1374. attributes: {
  1375. state: state,
  1376. time: time,
  1377. muted: isMuted,
  1378. volume: volume
  1379. }
  1380. });
  1381. }
  1382. else {
  1383. // in case of paused, in order to allow late users to join
  1384. // paused
  1385. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1386. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1387. value: url,
  1388. attributes: {
  1389. state: state,
  1390. time: time,
  1391. muted: isMuted,
  1392. volume: volume
  1393. }
  1394. });
  1395. }
  1396. });
  1397. room.addCommandListener(
  1398. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1399. if (attributes.state === 'stop') {
  1400. APP.UI.onSharedVideoStop(id, attributes);
  1401. }
  1402. else if (attributes.state === 'start') {
  1403. APP.UI.onSharedVideoStart(id, value, attributes);
  1404. }
  1405. else if (attributes.state === 'playing'
  1406. || attributes.state === 'pause') {
  1407. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1408. }
  1409. });
  1410. },
  1411. /**
  1412. * Adds any room listener.
  1413. * @param eventName one of the ConferenceEvents
  1414. * @param callBack the function to be called when the event occurs
  1415. */
  1416. addConferenceListener(eventName, callBack) {
  1417. room.on(eventName, callBack);
  1418. },
  1419. /**
  1420. * Inits list of current devices and event listener for device change.
  1421. * @private
  1422. */
  1423. _initDeviceList() {
  1424. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1425. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1426. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1427. // Ugly way to synchronize real device IDs with local
  1428. // storage and settings menu. This is a workaround until
  1429. // getConstraints() method will be implemented in browsers.
  1430. if (localAudio) {
  1431. APP.settings.setMicDeviceId(
  1432. localAudio.getDeviceId(), false);
  1433. }
  1434. if (localVideo) {
  1435. APP.settings.setCameraDeviceId(
  1436. localVideo.getDeviceId(), false);
  1437. }
  1438. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1439. APP.UI.onAvailableDevicesChanged(devices);
  1440. });
  1441. JitsiMeetJS.mediaDevices.addEventListener(
  1442. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1443. (devices) =>
  1444. window.setTimeout(
  1445. () => this._onDeviceListChanged(devices), 0));
  1446. }
  1447. },
  1448. /**
  1449. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1450. * handle change of available media devices.
  1451. * @private
  1452. * @param {MediaDeviceInfo[]} devices
  1453. * @returns {Promise}
  1454. */
  1455. _onDeviceListChanged(devices) {
  1456. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1457. // Event handler can be fired before direct
  1458. // enumerateDevices() call, so handle this situation here.
  1459. if (!currentDevices.audioinput &&
  1460. !currentDevices.videoinput &&
  1461. !currentDevices.audiooutput) {
  1462. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1463. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1464. }
  1465. let newDevices =
  1466. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1467. devices, this.isSharingScreen, localVideo, localAudio);
  1468. let promises = [];
  1469. let audioWasMuted = this.audioMuted;
  1470. let videoWasMuted = this.videoMuted;
  1471. let availableAudioInputDevices =
  1472. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1473. let availableVideoInputDevices =
  1474. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1475. if (typeof newDevices.audiooutput !== 'undefined') {
  1476. // Just ignore any errors in catch block.
  1477. promises.push(APP.settings
  1478. .setAudioOutputDeviceId(newDevices.audiooutput)
  1479. .catch());
  1480. }
  1481. promises.push(
  1482. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1483. createLocalTracks,
  1484. newDevices.videoinput,
  1485. newDevices.audioinput)
  1486. .then(tracks =>
  1487. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1488. .then(() => {
  1489. // If audio was muted before, or we unplugged current device
  1490. // and selected new one, then mute new audio track.
  1491. if (audioWasMuted ||
  1492. currentDevices.audioinput.length >
  1493. availableAudioInputDevices.length) {
  1494. muteLocalAudio(true);
  1495. }
  1496. // If video was muted before, or we unplugged current device
  1497. // and selected new one, then mute new video track.
  1498. if (videoWasMuted ||
  1499. currentDevices.videoinput.length >
  1500. availableVideoInputDevices.length) {
  1501. muteLocalVideo(true);
  1502. }
  1503. }));
  1504. return Promise.all(promises)
  1505. .then(() => {
  1506. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1507. APP.UI.onAvailableDevicesChanged(devices);
  1508. });
  1509. },
  1510. /**
  1511. * Toggles the local "raised hand" status.
  1512. */
  1513. maybeToggleRaisedHand() {
  1514. this.setRaisedHand(!this.isHandRaised);
  1515. },
  1516. /**
  1517. * Sets the local "raised hand" status to a particular value.
  1518. */
  1519. setRaisedHand(raisedHand) {
  1520. if (raisedHand !== this.isHandRaised)
  1521. {
  1522. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1523. this.isHandRaised = raisedHand;
  1524. // Advertise the updated status
  1525. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1526. // Update the view
  1527. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1528. }
  1529. },
  1530. /**
  1531. * Log event to callstats and analytics.
  1532. * @param {string} name the event name
  1533. * @param {int} value the value (it's int because google analytics supports
  1534. * only int).
  1535. * NOTE: Should be used after conference.init
  1536. */
  1537. logEvent(name, value) {
  1538. if(JitsiMeetJS.analytics) {
  1539. JitsiMeetJS.analytics.sendEvent(name, {value});
  1540. }
  1541. if(room) {
  1542. room.sendApplicationLog(JSON.stringify({name, value}));
  1543. }
  1544. },
  1545. /**
  1546. * Disconnect from the conference and optionally request user feedback.
  1547. * @param {boolean} [requestFeedback=false] if user feedback should be
  1548. * requested
  1549. */
  1550. hangup (requestFeedback = false) {
  1551. APP.UI.hideRingOverLay();
  1552. let requestFeedbackPromise = requestFeedback
  1553. ? APP.UI.requestFeedbackOnHangup()
  1554. // false - because the thank you dialog shouldn't be displayed
  1555. .catch(() => Promise.resolve(false))
  1556. : Promise.resolve(true);// true - because the thank you dialog
  1557. //should be displayed
  1558. // All promises are returning Promise.resolve to make Promise.all to
  1559. // be resolved when both Promises are finished. Otherwise Promise.all
  1560. // will reject on first rejected Promise and we can redirect the page
  1561. // before all operations are done.
  1562. Promise.all([
  1563. requestFeedbackPromise,
  1564. room.leave().then(disconnect, disconnect)
  1565. ]).then(values => {
  1566. APP.API.notifyReadyToClose();
  1567. maybeRedirectToWelcomePage(values[0]);
  1568. });
  1569. }
  1570. };