Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 61KB

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