You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 62KB

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