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

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