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.

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