選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 60KB

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