您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 73KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  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 { reload, reportError } from './modules/util/helpers';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import analytics from './modules/analytics/analytics';
  13. import EventEmitter from "events";
  14. import { showDesktopSharingButton } from './react/features/toolbox';
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. EMAIL_COMMAND,
  22. lockStateChanged
  23. } from './react/features/base/conference';
  24. import {
  25. updateDeviceList
  26. } from './react/features/base/devices';
  27. import {
  28. isFatalJitsiConnectionError
  29. } from './react/features/base/lib-jitsi-meet';
  30. import {
  31. localParticipantRoleChanged,
  32. participantJoined,
  33. participantLeft,
  34. participantRoleChanged,
  35. participantUpdated
  36. } from './react/features/base/participants';
  37. import {
  38. showDesktopPicker
  39. } from './react/features/desktop-picker';
  40. import {
  41. mediaPermissionPromptVisibilityChanged,
  42. suspendDetected
  43. } from './react/features/overlay';
  44. const ConnectionEvents = JitsiMeetJS.events.connection;
  45. const ConnectionErrors = JitsiMeetJS.errors.connection;
  46. const ConferenceEvents = JitsiMeetJS.events.conference;
  47. const ConferenceErrors = JitsiMeetJS.errors.conference;
  48. const TrackEvents = JitsiMeetJS.events.track;
  49. const TrackErrors = JitsiMeetJS.errors.track;
  50. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  51. const eventEmitter = new EventEmitter();
  52. let room;
  53. let connection;
  54. let localAudio, localVideo;
  55. let initialAudioMutedState = false, initialVideoMutedState = false;
  56. /**
  57. * Indicates whether extension external installation is in progress or not.
  58. */
  59. let DSExternalInstallationInProgress = false;
  60. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  61. /*
  62. * Logic to open a desktop picker put on the window global for
  63. * lib-jitsi-meet to detect and invoke
  64. */
  65. window.JitsiMeetScreenObtainer = {
  66. openDesktopPicker(onSourceChoose) {
  67. APP.store.dispatch(showDesktopPicker(onSourceChoose));
  68. }
  69. };
  70. /**
  71. * Known custom conference commands.
  72. */
  73. const commands = {
  74. AVATAR_ID: AVATAR_ID_COMMAND,
  75. AVATAR_URL: AVATAR_URL_COMMAND,
  76. CUSTOM_ROLE: "custom-role",
  77. EMAIL: EMAIL_COMMAND,
  78. ETHERPAD: "etherpad",
  79. SHARED_VIDEO: "shared-video"
  80. };
  81. /**
  82. * Max length of the display names. If we receive longer display name the
  83. * additional chars are going to be cut.
  84. */
  85. const MAX_DISPLAY_NAME_LENGTH = 50;
  86. /**
  87. * Open Connection. When authentication failed it shows auth dialog.
  88. * @param roomName the room name to use
  89. * @returns Promise<JitsiConnection>
  90. */
  91. function connect(roomName) {
  92. return openConnection({retry: true, roomName: roomName})
  93. .catch(function (err) {
  94. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  95. APP.UI.notifyTokenAuthFailed();
  96. } else {
  97. APP.UI.notifyConnectionFailed(err);
  98. }
  99. throw err;
  100. });
  101. }
  102. /**
  103. * Creates local media tracks and connects to room. Will show error
  104. * dialogs in case if accessing local microphone and/or camera failed. Will
  105. * show guidance overlay for users on how to give access to camera and/or
  106. * microphone,
  107. * @param {string} roomName
  108. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  109. */
  110. function createInitialLocalTracksAndConnect(roomName) {
  111. let audioAndVideoError,
  112. audioOnlyError;
  113. JitsiMeetJS.mediaDevices.addEventListener(
  114. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  115. browser =>
  116. APP.store.dispatch(
  117. mediaPermissionPromptVisibilityChanged(true, browser))
  118. );
  119. // First try to retrieve both audio and video.
  120. let tryCreateLocalTracks = createLocalTracks(
  121. { devices: ['audio', 'video'] }, true)
  122. .catch(err => {
  123. // If failed then try to retrieve only audio.
  124. audioAndVideoError = err;
  125. return createLocalTracks({ devices: ['audio'] }, true);
  126. })
  127. .catch(err => {
  128. // If audio failed too then just return empty array for tracks.
  129. audioOnlyError = err;
  130. return [];
  131. });
  132. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  133. .then(([tracks, con]) => {
  134. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  135. if (audioAndVideoError) {
  136. if (audioOnlyError) {
  137. // If both requests for 'audio' + 'video' and 'audio' only
  138. // failed, we assume that there is some problems with user's
  139. // microphone and show corresponding dialog.
  140. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  141. } else {
  142. // If request for 'audio' + 'video' failed, but request for
  143. // 'audio' only was OK, we assume that we had problems with
  144. // camera and show corresponding dialog.
  145. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  146. }
  147. }
  148. return [tracks, con];
  149. });
  150. }
  151. /**
  152. * Share data to other users.
  153. * @param command the command
  154. * @param {string} value new value
  155. */
  156. function sendData(command, value) {
  157. if(!room) {
  158. return;
  159. }
  160. room.removeCommand(command);
  161. room.sendCommand(command, {value: value});
  162. }
  163. /**
  164. * Sets up initially the properties of the local participant - email, avatarID,
  165. * avatarURL, displayName, etc.
  166. */
  167. function _setupLocalParticipantProperties() {
  168. const email = APP.settings.getEmail();
  169. email && sendData(commands.EMAIL, email);
  170. const avatarUrl = APP.settings.getAvatarUrl();
  171. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  172. if (!email && !avatarUrl) {
  173. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  174. }
  175. let nick = APP.settings.getDisplayName();
  176. if (config.useNicks && !nick) {
  177. nick = APP.UI.askForNickname();
  178. APP.settings.setDisplayName(nick);
  179. }
  180. nick && room.setDisplayName(nick);
  181. }
  182. /**
  183. * Get user nickname by user id.
  184. * @param {string} id user id
  185. * @returns {string?} user nickname or undefined if user is unknown.
  186. */
  187. function getDisplayName(id) {
  188. if (APP.conference.isLocalId(id)) {
  189. return APP.settings.getDisplayName();
  190. }
  191. let participant = room.getParticipantById(id);
  192. if (participant && participant.getDisplayName()) {
  193. return participant.getDisplayName();
  194. }
  195. }
  196. /**
  197. * Mute or unmute local audio stream if it exists.
  198. * @param {boolean} muted - if audio stream should be muted or unmuted.
  199. * @param {boolean} userInteraction - indicates if this local audio mute was a
  200. * result of user interaction
  201. */
  202. function muteLocalAudio(muted) {
  203. muteLocalMedia(localAudio, muted, 'Audio');
  204. }
  205. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  206. if (!localMedia) {
  207. return;
  208. }
  209. const method = muted ? 'mute' : 'unmute';
  210. localMedia[method]().catch(reason => {
  211. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  212. });
  213. }
  214. /**
  215. * Mute or unmute local video stream if it exists.
  216. * @param {boolean} muted if video stream should be muted or unmuted.
  217. */
  218. function muteLocalVideo(muted) {
  219. muteLocalMedia(localVideo, muted, 'Video');
  220. }
  221. /**
  222. * Check if the welcome page is enabled and redirects to it.
  223. * If requested show a thank you dialog before that.
  224. * If we have a close page enabled, redirect to it without
  225. * showing any other dialog.
  226. *
  227. * @param {object} options used to decide which particular close page to show
  228. * or if close page is disabled, whether we should show the thankyou dialog
  229. * @param {boolean} options.thankYouDialogVisible - whether we should
  230. * show thank you dialog
  231. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  232. */
  233. function maybeRedirectToWelcomePage(options) {
  234. // if close page is enabled redirect to it, without further action
  235. if (config.enableClosePage) {
  236. const { isGuest } = APP.store.getState()['features/jwt'];
  237. // save whether current user is guest or not, before navigating
  238. // to close page
  239. window.sessionStorage.setItem('guest', isGuest);
  240. assignWindowLocationPathname('static/'
  241. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  242. return;
  243. }
  244. // else: show thankYou dialog only if there is no feedback
  245. if (options.thankYouDialogVisible)
  246. APP.UI.messageHandler.openMessageDialog(
  247. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  248. // if Welcome page is enabled redirect to welcome page after 3 sec.
  249. if (config.enableWelcomePage) {
  250. setTimeout(() => {
  251. APP.settings.setWelcomePageEnabled(true);
  252. assignWindowLocationPathname('./');
  253. }, 3000);
  254. }
  255. }
  256. /**
  257. * Assigns a specific pathname to window.location.pathname taking into account
  258. * the context root of the Web app.
  259. *
  260. * @param {string} pathname - The pathname to assign to
  261. * window.location.pathname. If the specified pathname is relative, the context
  262. * root of the Web app will be prepended to the specified pathname before
  263. * assigning it to window.location.pathname.
  264. * @return {void}
  265. */
  266. function assignWindowLocationPathname(pathname) {
  267. const windowLocation = window.location;
  268. if (!pathname.startsWith('/')) {
  269. // XXX To support a deployment in a sub-directory, assume that the room
  270. // (name) is the last non-directory component of the path (name).
  271. let contextRoot = windowLocation.pathname;
  272. contextRoot
  273. = contextRoot.substring(0, contextRoot.lastIndexOf('/') + 1);
  274. // A pathname equal to ./ specifies the current directory. It will be
  275. // fine but pointless to include it because contextRoot is the current
  276. // directory.
  277. pathname.startsWith('./') && (pathname = pathname.substring(2));
  278. pathname = contextRoot + pathname;
  279. }
  280. windowLocation.pathname = pathname;
  281. }
  282. /**
  283. * Create local tracks of specified types.
  284. * @param {Object} options
  285. * @param {string[]} options.devices - required track types
  286. * ('audio', 'video' etc.)
  287. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  288. * undefined - one from settings will be used
  289. * @param {string|null} (options.micDeviceId) - microphone device id, if
  290. * undefined - one from settings will be used
  291. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  292. * for gUM permission prompt
  293. * @returns {Promise<JitsiLocalTrack[]>}
  294. */
  295. function createLocalTracks(options, checkForPermissionPrompt) {
  296. options || (options = {});
  297. return JitsiMeetJS
  298. .createLocalTracks({
  299. // copy array to avoid mutations inside library
  300. devices: options.devices.slice(0),
  301. resolution: config.resolution,
  302. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  303. options.cameraDeviceId === null
  304. ? APP.settings.getCameraDeviceId()
  305. : options.cameraDeviceId,
  306. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  307. options.micDeviceId === null
  308. ? APP.settings.getMicDeviceId()
  309. : options.micDeviceId,
  310. // adds any ff fake device settings if any
  311. firefox_fake_device: config.firefox_fake_device,
  312. desktopSharingExtensionExternalInstallation:
  313. options.desktopSharingExtensionExternalInstallation
  314. }, checkForPermissionPrompt).then( (tracks) => {
  315. tracks.forEach((track) => {
  316. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  317. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  318. });
  319. return tracks;
  320. }).catch(function (err) {
  321. logger.error(
  322. 'failed to create local tracks', options.devices, err);
  323. return Promise.reject(err);
  324. });
  325. }
  326. class ConferenceConnector {
  327. constructor(resolve, reject) {
  328. this._resolve = resolve;
  329. this._reject = reject;
  330. this.reconnectTimeout = null;
  331. room.on(ConferenceEvents.CONFERENCE_JOINED,
  332. this._handleConferenceJoined.bind(this));
  333. room.on(ConferenceEvents.CONFERENCE_FAILED,
  334. this._onConferenceFailed.bind(this));
  335. room.on(ConferenceEvents.CONFERENCE_ERROR,
  336. this._onConferenceError.bind(this));
  337. }
  338. _handleConferenceFailed(err) {
  339. this._unsubscribe();
  340. this._reject(err);
  341. }
  342. _onConferenceFailed(err, ...params) {
  343. APP.store.dispatch(conferenceFailed(room, err, ...params));
  344. logger.error('CONFERENCE FAILED:', err, ...params);
  345. APP.UI.hideRingOverLay();
  346. switch (err) {
  347. case ConferenceErrors.CONNECTION_ERROR:
  348. {
  349. let [msg] = params;
  350. APP.UI.notifyConnectionFailed(msg);
  351. }
  352. break;
  353. case ConferenceErrors.NOT_ALLOWED_ERROR:
  354. {
  355. // let's show some auth not allowed page
  356. assignWindowLocationPathname('static/authError.html');
  357. }
  358. break;
  359. // not enough rights to create conference
  360. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  361. // Schedule reconnect to check if someone else created the room.
  362. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  363. const { password }
  364. = APP.store.getState()['features/base/conference'];
  365. AuthHandler.requireAuth(room, password);
  366. }
  367. break;
  368. case ConferenceErrors.RESERVATION_ERROR:
  369. {
  370. let [code, msg] = params;
  371. APP.UI.notifyReservationError(code, msg);
  372. }
  373. break;
  374. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  375. APP.UI.notifyGracefulShutdown();
  376. break;
  377. case ConferenceErrors.JINGLE_FATAL_ERROR:
  378. APP.UI.notifyInternalError();
  379. break;
  380. case ConferenceErrors.CONFERENCE_DESTROYED:
  381. {
  382. let [reason] = params;
  383. APP.UI.hideStats();
  384. APP.UI.notifyConferenceDestroyed(reason);
  385. }
  386. break;
  387. // FIXME FOCUS_DISCONNECTED is confusing event name.
  388. // What really happens there is that the library is not ready yet,
  389. // because Jicofo is not available, but it is going to give
  390. // it another try.
  391. case ConferenceErrors.FOCUS_DISCONNECTED:
  392. {
  393. let [focus, retrySec] = params;
  394. APP.UI.notifyFocusDisconnected(focus, retrySec);
  395. }
  396. break;
  397. case ConferenceErrors.FOCUS_LEFT:
  398. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  399. // FIXME the conference should be stopped by the library and not by
  400. // the app. Both the errors above are unrecoverable from the library
  401. // perspective.
  402. room.leave().then(() => connection.disconnect());
  403. break;
  404. case ConferenceErrors.CONFERENCE_MAX_USERS:
  405. connection.disconnect();
  406. APP.UI.notifyMaxUsersLimitReached();
  407. break;
  408. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  409. reload();
  410. break;
  411. default:
  412. this._handleConferenceFailed(err, ...params);
  413. }
  414. }
  415. _onConferenceError(err, ...params) {
  416. logger.error('CONFERENCE Error:', err, params);
  417. switch (err) {
  418. case ConferenceErrors.CHAT_ERROR:
  419. {
  420. let [code, msg] = params;
  421. APP.UI.showChatError(code, msg);
  422. }
  423. break;
  424. default:
  425. logger.error("Unknown error.", err);
  426. }
  427. }
  428. _unsubscribe() {
  429. room.off(
  430. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  431. room.off(
  432. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  433. if (this.reconnectTimeout !== null) {
  434. clearTimeout(this.reconnectTimeout);
  435. }
  436. AuthHandler.closeAuth();
  437. }
  438. _handleConferenceJoined() {
  439. this._unsubscribe();
  440. this._resolve();
  441. }
  442. connect() {
  443. room.join();
  444. }
  445. }
  446. /**
  447. * Disconnects the connection.
  448. * @returns resolved Promise. We need this in order to make the Promise.all
  449. * call in hangup() to resolve when all operations are finished.
  450. */
  451. function disconnect() {
  452. connection.disconnect();
  453. APP.API.notifyConferenceLeft(APP.conference.roomName);
  454. return Promise.resolve();
  455. }
  456. /**
  457. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  458. *
  459. * @param {JitsiMeetJS.connection.error} error - The reported error.
  460. * @returns {void}
  461. * @private
  462. */
  463. function _connectionFailedHandler(error) {
  464. if (isFatalJitsiConnectionError(error)) {
  465. APP.connection.removeEventListener(
  466. ConnectionEvents.CONNECTION_FAILED,
  467. _connectionFailedHandler);
  468. if (room)
  469. room.leave();
  470. }
  471. }
  472. export default {
  473. isModerator: false,
  474. audioMuted: false,
  475. videoMuted: false,
  476. isSharingScreen: false,
  477. isDesktopSharingEnabled: false,
  478. /*
  479. * Whether the local "raisedHand" flag is on.
  480. */
  481. isHandRaised: false,
  482. /*
  483. * Whether the local participant is the dominant speaker in the conference.
  484. */
  485. isDominantSpeaker: false,
  486. /**
  487. * Open new connection and join to the conference.
  488. * @param {object} options
  489. * @param {string} roomName name of the conference
  490. * @returns {Promise}
  491. */
  492. init(options) {
  493. this.roomName = options.roomName;
  494. // attaches global error handler, if there is already one, respect it
  495. if(JitsiMeetJS.getGlobalOnErrorHandler){
  496. var oldOnErrorHandler = window.onerror;
  497. window.onerror = function (message, source, lineno, colno, error) {
  498. JitsiMeetJS.getGlobalOnErrorHandler(
  499. message, source, lineno, colno, error);
  500. if(oldOnErrorHandler)
  501. oldOnErrorHandler(message, source, lineno, colno, error);
  502. };
  503. var oldOnUnhandledRejection = window.onunhandledrejection;
  504. window.onunhandledrejection = function(event) {
  505. JitsiMeetJS.getGlobalOnErrorHandler(
  506. null, null, null, null, event.reason);
  507. if(oldOnUnhandledRejection)
  508. oldOnUnhandledRejection(event);
  509. };
  510. }
  511. return JitsiMeetJS.init(
  512. Object.assign(
  513. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  514. ).then(() => {
  515. analytics.init();
  516. return createInitialLocalTracksAndConnect(options.roomName);
  517. }).then(([tracks, con]) => {
  518. tracks.forEach(track => {
  519. if((track.isAudioTrack() && initialAudioMutedState)
  520. || (track.isVideoTrack() && initialVideoMutedState)) {
  521. track.mute();
  522. }
  523. });
  524. logger.log('initialized with %s local tracks', tracks.length);
  525. con.addEventListener(
  526. ConnectionEvents.CONNECTION_FAILED,
  527. _connectionFailedHandler);
  528. APP.connection = connection = con;
  529. this.isDesktopSharingEnabled =
  530. JitsiMeetJS.isDesktopSharingEnabled();
  531. eventEmitter.emit(
  532. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  533. this.isDesktopSharingEnabled);
  534. APP.store.dispatch(showDesktopSharingButton());
  535. this._createRoom(tracks);
  536. APP.remoteControl.init();
  537. if (UIUtil.isButtonEnabled('contacts')
  538. && !interfaceConfig.filmStripOnly) {
  539. APP.UI.ContactList = new ContactList(room);
  540. }
  541. // if user didn't give access to mic or camera or doesn't have
  542. // them at all, we disable corresponding toolbar buttons
  543. if (!tracks.find((t) => t.isAudioTrack())) {
  544. APP.UI.setMicrophoneButtonEnabled(false);
  545. }
  546. if (!tracks.find((t) => t.isVideoTrack())) {
  547. APP.UI.setCameraButtonEnabled(false);
  548. }
  549. this._initDeviceList();
  550. if (config.iAmRecorder)
  551. this.recorder = new Recorder();
  552. // XXX The API will take care of disconnecting from the XMPP
  553. // server (and, thus, leaving the room) on unload.
  554. return new Promise((resolve, reject) => {
  555. (new ConferenceConnector(resolve, reject)).connect();
  556. });
  557. });
  558. },
  559. /**
  560. * Check if id is id of the local user.
  561. * @param {string} id id to check
  562. * @returns {boolean}
  563. */
  564. isLocalId(id) {
  565. return this.getMyUserId() === id;
  566. },
  567. /**
  568. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  569. * @param mute true for mute and false for unmute.
  570. */
  571. muteAudio(mute) {
  572. muteLocalAudio(mute);
  573. },
  574. /**
  575. * Returns whether local audio is muted or not.
  576. * @returns {boolean}
  577. */
  578. isLocalAudioMuted() {
  579. return this.audioMuted;
  580. },
  581. /**
  582. * Simulates toolbar button click for audio mute. Used by shortcuts
  583. * and API.
  584. * @param {boolean} force - If the track is not created, the operation
  585. * will be executed after the track is created. Otherwise the operation
  586. * will be ignored.
  587. */
  588. toggleAudioMuted(force = false) {
  589. if(!localAudio && force) {
  590. initialAudioMutedState = !initialAudioMutedState;
  591. return;
  592. }
  593. this.muteAudio(!this.audioMuted);
  594. },
  595. /**
  596. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  597. * @param mute true for mute and false for unmute.
  598. */
  599. muteVideo(mute) {
  600. muteLocalVideo(mute);
  601. },
  602. /**
  603. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  604. * @param {boolean} force - If the track is not created, the operation
  605. * will be executed after the track is created. Otherwise the operation
  606. * will be ignored.
  607. */
  608. toggleVideoMuted(force = false) {
  609. if(!localVideo && force) {
  610. initialVideoMutedState = !initialVideoMutedState;
  611. return;
  612. }
  613. this.muteVideo(!this.videoMuted);
  614. },
  615. /**
  616. * Retrieve list of conference participants (without local user).
  617. * @returns {JitsiParticipant[]}
  618. */
  619. listMembers() {
  620. return room.getParticipants();
  621. },
  622. /**
  623. * Retrieve list of ids of conference participants (without local user).
  624. * @returns {string[]}
  625. */
  626. listMembersIds() {
  627. return room.getParticipants().map(p => p.getId());
  628. },
  629. /**
  630. * Checks whether the participant identified by id is a moderator.
  631. * @id id to search for participant
  632. * @return {boolean} whether the participant is moderator
  633. */
  634. isParticipantModerator(id) {
  635. let user = room.getParticipantById(id);
  636. return user && user.isModerator();
  637. },
  638. /**
  639. * Check if SIP is supported.
  640. * @returns {boolean}
  641. */
  642. sipGatewayEnabled() {
  643. return room.isSIPCallingSupported();
  644. },
  645. get membersCount() {
  646. return room.getParticipants().length + 1;
  647. },
  648. /**
  649. * Returns true if the callstats integration is enabled, otherwise returns
  650. * false.
  651. *
  652. * @returns true if the callstats integration is enabled, otherwise returns
  653. * false.
  654. */
  655. isCallstatsEnabled() {
  656. return room && room.isCallstatsEnabled();
  657. },
  658. /**
  659. * Sends the given feedback through CallStats if enabled.
  660. *
  661. * @param overallFeedback an integer between 1 and 5 indicating the
  662. * user feedback
  663. * @param detailedFeedback detailed feedback from the user. Not yet used
  664. */
  665. sendFeedback(overallFeedback, detailedFeedback) {
  666. return room.sendFeedback (overallFeedback, detailedFeedback);
  667. },
  668. /**
  669. * Get speaker stats that track total dominant speaker time.
  670. *
  671. * @returns {object} A hash with keys being user ids and values being the
  672. * library's SpeakerStats model used for calculating time as dominant
  673. * speaker.
  674. */
  675. getSpeakerStats() {
  676. return room.getSpeakerStats();
  677. },
  678. /**
  679. * Returns the connection times stored in the library.
  680. */
  681. getConnectionTimes() {
  682. return this._room.getConnectionTimes();
  683. },
  684. // used by torture currently
  685. isJoined() {
  686. return this._room
  687. && this._room.isJoined();
  688. },
  689. getConnectionState() {
  690. return this._room
  691. && this._room.getConnectionState();
  692. },
  693. /**
  694. * Obtains current P2P ICE connection state.
  695. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  696. * P2P connection
  697. */
  698. getP2PConnectionState() {
  699. return this._room
  700. && this._room.getP2PConnectionState();
  701. },
  702. /**
  703. * Starts P2P (for tests only)
  704. * @private
  705. */
  706. _startP2P() {
  707. try {
  708. this._room && this._room.startP2PSession();
  709. } catch (error) {
  710. logger.error("Start P2P failed", error);
  711. throw error;
  712. }
  713. },
  714. /**
  715. * Stops P2P (for tests only)
  716. * @private
  717. */
  718. _stopP2P() {
  719. try {
  720. this._room && this._room.stopP2PSession();
  721. } catch (error) {
  722. logger.error("Stop P2P failed", error);
  723. throw error;
  724. }
  725. },
  726. /**
  727. * Checks whether or not our connection is currently in interrupted and
  728. * reconnect attempts are in progress.
  729. *
  730. * @returns {boolean} true if the connection is in interrupted state or
  731. * false otherwise.
  732. */
  733. isConnectionInterrupted() {
  734. return this._room.isConnectionInterrupted();
  735. },
  736. /**
  737. * Finds JitsiParticipant for given id.
  738. *
  739. * @param {string} id participant's identifier(MUC nickname).
  740. *
  741. * @returns {JitsiParticipant|null} participant instance for given id or
  742. * null if not found.
  743. */
  744. getParticipantById(id) {
  745. return room ? room.getParticipantById(id) : null;
  746. },
  747. /**
  748. * Get participant connection status for the participant.
  749. *
  750. * @param {string} id participant's identifier(MUC nickname)
  751. *
  752. * @returns {ParticipantConnectionStatus|null} the status of the participant
  753. * or null if no such participant is found or participant is the local user.
  754. */
  755. getParticipantConnectionStatus(id) {
  756. let participant = this.getParticipantById(id);
  757. return participant ? participant.getConnectionStatus() : null;
  758. },
  759. /**
  760. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  761. * the given <tt>id</tt>.
  762. *
  763. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  764. *
  765. * @return {string} the participant's display name or the default string if
  766. * absent.
  767. */
  768. getParticipantDisplayName(id) {
  769. let displayName = getDisplayName(id);
  770. if (displayName) {
  771. return displayName;
  772. } else {
  773. if (APP.conference.isLocalId(id)) {
  774. return APP.translation.generateTranslationHTML(
  775. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  776. } else {
  777. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  778. }
  779. }
  780. },
  781. getMyUserId() {
  782. return this._room
  783. && this._room.myUserId();
  784. },
  785. /**
  786. * Indicates if recording is supported in this conference.
  787. */
  788. isRecordingSupported() {
  789. return this._room && this._room.isRecordingSupported();
  790. },
  791. /**
  792. * Returns the recording state or undefined if the room is not defined.
  793. */
  794. getRecordingState() {
  795. return (this._room) ? this._room.getRecordingState() : undefined;
  796. },
  797. /**
  798. * Will be filled with values only when config.debug is enabled.
  799. * Its used by torture to check audio levels.
  800. */
  801. audioLevelsMap: {},
  802. /**
  803. * Returns the stored audio level (stored only if config.debug is enabled)
  804. * @param id the id for the user audio level to return (the id value is
  805. * returned for the participant using getMyUserId() method)
  806. */
  807. getPeerSSRCAudioLevel(id) {
  808. return this.audioLevelsMap[id];
  809. },
  810. /**
  811. * @return {number} the number of participants in the conference with at
  812. * least one track.
  813. */
  814. getNumberOfParticipantsWithTracks() {
  815. return this._room.getParticipants()
  816. .filter((p) => p.getTracks().length > 0)
  817. .length;
  818. },
  819. /**
  820. * Returns the stats.
  821. */
  822. getStats() {
  823. return room.connectionQuality.getStats();
  824. },
  825. // end used by torture
  826. getLogs() {
  827. return room.getLogs();
  828. },
  829. /**
  830. * Download logs, a function that can be called from console while
  831. * debugging.
  832. * @param filename (optional) specify target filename
  833. */
  834. saveLogs(filename = 'meetlog.json') {
  835. // this can be called from console and will not have reference to this
  836. // that's why we reference the global var
  837. let logs = APP.conference.getLogs();
  838. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  839. let elem = document.createElement('a');
  840. elem.download = filename;
  841. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  842. elem.dataset.downloadurl
  843. = ['text/json', elem.download, elem.href].join(':');
  844. elem.dispatchEvent(new MouseEvent('click', {
  845. view: window,
  846. bubbles: true,
  847. cancelable: false
  848. }));
  849. },
  850. /**
  851. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  852. * desire to keep room private to this instance and (2) the need of other
  853. * modules to send and receive commands to and from participants.
  854. * Eventually, this instance remains in control with respect to the
  855. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  856. * JitsiConference) is to be used in the implementation of the Command(s)
  857. * API of this instance.
  858. */
  859. commands: {
  860. /**
  861. * Known custom conference commands.
  862. */
  863. defaults: commands,
  864. /**
  865. * Receives notifications from other participants about commands aka
  866. * custom events (sent by sendCommand or sendCommandOnce methods).
  867. * @param command {String} the name of the command
  868. * @param handler {Function} handler for the command
  869. */
  870. addCommandListener () {
  871. room.addCommandListener.apply(room, arguments);
  872. },
  873. /**
  874. * Removes command.
  875. * @param name {String} the name of the command.
  876. */
  877. removeCommand () {
  878. room.removeCommand.apply(room, arguments);
  879. },
  880. /**
  881. * Sends command.
  882. * @param name {String} the name of the command.
  883. * @param values {Object} with keys and values that will be sent.
  884. */
  885. sendCommand () {
  886. room.sendCommand.apply(room, arguments);
  887. },
  888. /**
  889. * Sends command one time.
  890. * @param name {String} the name of the command.
  891. * @param values {Object} with keys and values that will be sent.
  892. */
  893. sendCommandOnce () {
  894. room.sendCommandOnce.apply(room, arguments);
  895. }
  896. },
  897. _createRoom (localTracks) {
  898. room = connection.initJitsiConference(APP.conference.roomName,
  899. this._getConferenceOptions());
  900. this._setLocalAudioVideoStreams(localTracks);
  901. this._room = room; // FIXME do not use this
  902. _setupLocalParticipantProperties();
  903. this._setupListeners();
  904. },
  905. /**
  906. * Sets local video and audio streams.
  907. * @param {JitsiLocalTrack[]} tracks=[]
  908. * @returns {Promise[]}
  909. * @private
  910. */
  911. _setLocalAudioVideoStreams(tracks = []) {
  912. return tracks.map(track => {
  913. if (track.isAudioTrack()) {
  914. return this.useAudioStream(track);
  915. } else if (track.isVideoTrack()) {
  916. return this.useVideoStream(track);
  917. } else {
  918. logger.error(
  919. "Ignored not an audio nor a video track: ", track);
  920. return Promise.resolve();
  921. }
  922. });
  923. },
  924. _getConferenceOptions() {
  925. let options = config;
  926. if(config.enableRecording && !config.recordingType) {
  927. options.recordingType = (config.hosts &&
  928. (typeof config.hosts.jirecon != "undefined"))?
  929. "jirecon" : "colibri";
  930. }
  931. return options;
  932. },
  933. /**
  934. * Start using provided video stream.
  935. * Stops previous video stream.
  936. * @param {JitsiLocalTrack} [stream] new stream to use or null
  937. * @returns {Promise}
  938. */
  939. useVideoStream(newStream) {
  940. return room.replaceTrack(localVideo, newStream)
  941. .then(() => {
  942. // We call dispose after doing the replace because
  943. // dispose will try and do a new o/a after the
  944. // track removes itself. Doing it after means
  945. // the JitsiLocalTrack::conference member is already
  946. // cleared, so it won't try and do the o/a
  947. if (localVideo) {
  948. localVideo.dispose();
  949. }
  950. localVideo = newStream;
  951. if (newStream) {
  952. this.videoMuted = newStream.isMuted();
  953. this.isSharingScreen = newStream.videoType === 'desktop';
  954. APP.UI.addLocalStream(newStream);
  955. newStream.videoType === 'camera'
  956. && APP.UI.setCameraButtonEnabled(true);
  957. } else {
  958. this.videoMuted = false;
  959. this.isSharingScreen = false;
  960. }
  961. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  962. APP.UI.updateDesktopSharingButtons();
  963. });
  964. },
  965. /**
  966. * Start using provided audio stream.
  967. * Stops previous audio stream.
  968. * @param {JitsiLocalTrack} [stream] new stream to use or null
  969. * @returns {Promise}
  970. */
  971. useAudioStream(newStream) {
  972. return room.replaceTrack(localAudio, newStream)
  973. .then(() => {
  974. // We call dispose after doing the replace because
  975. // dispose will try and do a new o/a after the
  976. // track removes itself. Doing it after means
  977. // the JitsiLocalTrack::conference member is already
  978. // cleared, so it won't try and do the o/a
  979. if (localAudio) {
  980. localAudio.dispose();
  981. }
  982. localAudio = newStream;
  983. if (newStream) {
  984. this.audioMuted = newStream.isMuted();
  985. APP.UI.addLocalStream(newStream);
  986. } else {
  987. this.audioMuted = false;
  988. }
  989. APP.UI.setMicrophoneButtonEnabled(true);
  990. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  991. });
  992. },
  993. /**
  994. * Triggers a tooltip to display when a feature was attempted to be used
  995. * while in audio only mode.
  996. *
  997. * @param {string} featureName - The name of the feature that attempted to
  998. * toggle.
  999. * @private
  1000. * @returns {void}
  1001. */
  1002. _displayAudioOnlyTooltip(featureName) {
  1003. let tooltipElementId = null;
  1004. switch (featureName) {
  1005. case 'screenShare':
  1006. tooltipElementId = '#screenshareWhileAudioOnly';
  1007. break;
  1008. case 'videoMute':
  1009. tooltipElementId = '#unmuteWhileAudioOnly';
  1010. break;
  1011. }
  1012. if (tooltipElementId) {
  1013. APP.UI.showToolbar(6000);
  1014. APP.UI.showCustomToolbarPopup(
  1015. tooltipElementId, true, 5000);
  1016. }
  1017. },
  1018. /**
  1019. * Returns whether or not the conference is currently in audio only mode.
  1020. *
  1021. * @returns {boolean}
  1022. */
  1023. isAudioOnly() {
  1024. return Boolean(
  1025. APP.store.getState()['features/base/conference'].audioOnly);
  1026. },
  1027. videoSwitchInProgress: false,
  1028. toggleScreenSharing(shareScreen = !this.isSharingScreen) {
  1029. if (this.videoSwitchInProgress) {
  1030. logger.warn("Switch in progress.");
  1031. return;
  1032. }
  1033. if (!this.isDesktopSharingEnabled) {
  1034. logger.warn("Cannot toggle screen sharing: not supported.");
  1035. return;
  1036. }
  1037. if (this.isAudioOnly()) {
  1038. this._displayAudioOnlyTooltip('screenShare');
  1039. return;
  1040. }
  1041. this.videoSwitchInProgress = true;
  1042. let externalInstallation = false;
  1043. if (shareScreen) {
  1044. this.screenSharingPromise = createLocalTracks({
  1045. devices: ['desktop'],
  1046. desktopSharingExtensionExternalInstallation: {
  1047. interval: 500,
  1048. checkAgain: () => {
  1049. return DSExternalInstallationInProgress;
  1050. },
  1051. listener: (status, url) => {
  1052. switch(status) {
  1053. case "waitingForExtension":
  1054. DSExternalInstallationInProgress = true;
  1055. externalInstallation = true;
  1056. APP.UI.showExtensionExternalInstallationDialog(
  1057. url);
  1058. break;
  1059. case "extensionFound":
  1060. if(externalInstallation) //close the dialog
  1061. $.prompt.close();
  1062. break;
  1063. default:
  1064. //Unknown status
  1065. }
  1066. }
  1067. }
  1068. }).then(([stream]) => {
  1069. DSExternalInstallationInProgress = false;
  1070. // close external installation dialog on success.
  1071. if(externalInstallation)
  1072. $.prompt.close();
  1073. stream.on(
  1074. TrackEvents.LOCAL_TRACK_STOPPED,
  1075. () => {
  1076. // if stream was stopped during screensharing session
  1077. // then we should switch to video
  1078. // otherwise we stopped it because we already switched
  1079. // to video, so nothing to do here
  1080. if (this.isSharingScreen) {
  1081. this.toggleScreenSharing(false);
  1082. }
  1083. }
  1084. );
  1085. return this.useVideoStream(stream);
  1086. }).then(() => {
  1087. this.videoSwitchInProgress = false;
  1088. JitsiMeetJS.analytics.sendEvent(
  1089. 'conference.sharingDesktop.start');
  1090. logger.log('sharing local desktop');
  1091. }).catch((err) => {
  1092. // close external installation dialog to show the error.
  1093. if(externalInstallation)
  1094. $.prompt.close();
  1095. this.videoSwitchInProgress = false;
  1096. this.toggleScreenSharing(false);
  1097. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1098. return;
  1099. }
  1100. logger.error('failed to share local desktop', err);
  1101. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1102. APP.UI.showExtensionRequiredDialog(
  1103. config.desktopSharingFirefoxExtensionURL
  1104. );
  1105. return;
  1106. }
  1107. // Handling:
  1108. // TrackErrors.PERMISSION_DENIED
  1109. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1110. // TrackErrors.GENERAL
  1111. // and any other
  1112. let dialogTxt;
  1113. let dialogTitleKey;
  1114. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1115. dialogTxt = APP.translation.generateTranslationHTML(
  1116. "dialog.screenSharingPermissionDeniedError");
  1117. dialogTitleKey = "dialog.error";
  1118. } else {
  1119. dialogTxt = APP.translation.generateTranslationHTML(
  1120. "dialog.failtoinstall");
  1121. dialogTitleKey = "dialog.permissionDenied";
  1122. }
  1123. APP.UI.messageHandler.openDialog(
  1124. dialogTitleKey, dialogTxt, false);
  1125. });
  1126. } else {
  1127. APP.remoteControl.receiver.stop();
  1128. this.screenSharingPromise = createLocalTracks(
  1129. { devices: ['video'] })
  1130. .then(
  1131. ([stream]) => this.useVideoStream(stream)
  1132. ).then(() => {
  1133. this.videoSwitchInProgress = false;
  1134. JitsiMeetJS.analytics.sendEvent(
  1135. 'conference.sharingDesktop.stop');
  1136. logger.log('sharing local video');
  1137. }).catch((err) => {
  1138. this.useVideoStream(null);
  1139. this.videoSwitchInProgress = false;
  1140. logger.error('failed to share local video', err);
  1141. });
  1142. }
  1143. },
  1144. /**
  1145. * Setup interaction between conference and UI.
  1146. */
  1147. _setupListeners() {
  1148. // add local streams when joined to the conference
  1149. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1150. APP.store.dispatch(conferenceJoined(room));
  1151. APP.UI.mucJoined();
  1152. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1153. APP.UI.markVideoInterrupted(false);
  1154. });
  1155. room.on(
  1156. ConferenceEvents.CONFERENCE_LEFT,
  1157. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1158. room.on(
  1159. ConferenceEvents.AUTH_STATUS_CHANGED,
  1160. function (authEnabled, authLogin) {
  1161. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1162. }
  1163. );
  1164. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1165. user => APP.UI.onUserFeaturesChanged(user));
  1166. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1167. if (user.isHidden())
  1168. return;
  1169. APP.store.dispatch(participantJoined({
  1170. id,
  1171. name: user.getDisplayName(),
  1172. role: user.getRole()
  1173. }));
  1174. logger.log('USER %s connnected', id, user);
  1175. APP.API.notifyUserJoined(id);
  1176. APP.UI.addUser(user);
  1177. // check the roles for the new user and reflect them
  1178. APP.UI.updateUserRole(user);
  1179. });
  1180. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1181. APP.store.dispatch(participantLeft(id, user));
  1182. logger.log('USER %s LEFT', id, user);
  1183. APP.API.notifyUserLeft(id);
  1184. APP.UI.removeUser(id, user.getDisplayName());
  1185. APP.UI.onSharedVideoStop(id);
  1186. });
  1187. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1188. if (this.isLocalId(id)) {
  1189. logger.info(`My role changed, new role: ${role}`);
  1190. APP.store.dispatch(localParticipantRoleChanged(role));
  1191. if (this.isModerator !== room.isModerator()) {
  1192. this.isModerator = room.isModerator();
  1193. APP.UI.updateLocalRole(room.isModerator());
  1194. }
  1195. } else {
  1196. APP.store.dispatch(participantRoleChanged(id, role));
  1197. let user = room.getParticipantById(id);
  1198. if (user) {
  1199. APP.UI.updateUserRole(user);
  1200. }
  1201. }
  1202. });
  1203. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1204. if(!track || track.isLocal())
  1205. return;
  1206. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1207. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1208. });
  1209. APP.UI.addRemoteStream(track);
  1210. });
  1211. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1212. if(!track || track.isLocal())
  1213. return;
  1214. APP.UI.removeRemoteStream(track);
  1215. });
  1216. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1217. if(!track)
  1218. return;
  1219. const handler = (track.getType() === "audio")?
  1220. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1221. let id;
  1222. const mute = track.isMuted();
  1223. if(track.isLocal()){
  1224. id = APP.conference.getMyUserId();
  1225. if(track.getType() === "audio") {
  1226. this.audioMuted = mute;
  1227. } else {
  1228. this.videoMuted = mute;
  1229. }
  1230. } else {
  1231. id = track.getParticipantId();
  1232. }
  1233. handler(id , mute);
  1234. });
  1235. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1236. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1237. lvl = 0;
  1238. }
  1239. if(config.debug)
  1240. {
  1241. this.audioLevelsMap[id] = lvl;
  1242. if(config.debugAudioLevels)
  1243. logger.log("AudioLevel:" + id + "/" + lvl);
  1244. }
  1245. APP.UI.setAudioLevel(id, lvl);
  1246. });
  1247. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1248. APP.UI.showToolbar(6000);
  1249. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1250. });
  1251. room.on(
  1252. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1253. (leavingIds, enteringIds) => {
  1254. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1255. });
  1256. room.on(
  1257. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1258. id => {
  1259. APP.UI.participantConnectionStatusChanged(id);
  1260. });
  1261. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1262. if (this.isLocalId(id)) {
  1263. this.isDominantSpeaker = true;
  1264. this.setRaisedHand(false);
  1265. } else {
  1266. this.isDominantSpeaker = false;
  1267. var participant = room.getParticipantById(id);
  1268. if (participant) {
  1269. APP.UI.setRaisedHandStatus(participant, false);
  1270. }
  1271. }
  1272. APP.UI.markDominantSpeaker(id);
  1273. });
  1274. if (!interfaceConfig.filmStripOnly) {
  1275. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1276. APP.UI.markVideoInterrupted(true);
  1277. });
  1278. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1279. APP.UI.markVideoInterrupted(false);
  1280. });
  1281. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1282. let nick = getDisplayName(id);
  1283. APP.API.notifyReceivedChatMessage({
  1284. id,
  1285. nick,
  1286. body,
  1287. ts
  1288. });
  1289. APP.UI.addMessage(id, nick, body, ts);
  1290. });
  1291. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1292. APP.API.notifySendingChatMessage(message);
  1293. room.sendTextMessage(message);
  1294. });
  1295. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1296. try {
  1297. // do not try to select participant if there is none (we
  1298. // are alone in the room), otherwise an error will be
  1299. // thrown cause reporting mechanism is not available
  1300. // (datachannels currently)
  1301. if (room.getParticipants().length === 0)
  1302. return;
  1303. room.selectParticipant(id);
  1304. } catch (e) {
  1305. JitsiMeetJS.analytics.sendEvent(
  1306. 'selectParticipant.failed');
  1307. reportError(e);
  1308. }
  1309. });
  1310. APP.UI.addListener(
  1311. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1312. () => this._displayAudioOnlyTooltip('videoMute'));
  1313. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1314. (smallVideo, isPinned) => {
  1315. let smallVideoId = smallVideo.getId();
  1316. let isLocal = APP.conference.isLocalId(smallVideoId);
  1317. let eventName
  1318. = (isPinned ? "pinned" : "unpinned") + "." +
  1319. (isLocal ? "local" : "remote");
  1320. let participantCount = room.getParticipantCount();
  1321. JitsiMeetJS.analytics.sendEvent(
  1322. eventName,
  1323. { value: participantCount });
  1324. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1325. // the participant is on the large video ?
  1326. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1327. && !isLocal) {
  1328. // When the library starts supporting multiple pins we
  1329. // would pass the isPinned parameter together with the
  1330. // identifier, but currently we send null to indicate that
  1331. // we unpin the last pinned.
  1332. try {
  1333. room.pinParticipant(isPinned ? smallVideoId : null);
  1334. } catch (e) {
  1335. reportError(e);
  1336. }
  1337. }
  1338. });
  1339. }
  1340. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1341. APP.UI.showLocalConnectionInterrupted(true);
  1342. });
  1343. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1344. APP.UI.showLocalConnectionInterrupted(false);
  1345. });
  1346. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1347. const formattedDisplayName
  1348. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1349. APP.store.dispatch(participantUpdated({
  1350. id,
  1351. name: formattedDisplayName
  1352. }));
  1353. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1354. APP.UI.changeDisplayName(id, formattedDisplayName);
  1355. });
  1356. room.on(
  1357. ConferenceEvents.LOCK_STATE_CHANGED,
  1358. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1359. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1360. (participant, name, oldValue, newValue) => {
  1361. if (name === "raisedHand") {
  1362. APP.UI.setRaisedHandStatus(participant, newValue);
  1363. }
  1364. });
  1365. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1366. logger.log("Received recorder status change: ", status, error);
  1367. APP.UI.updateRecordingState(status);
  1368. });
  1369. room.on(ConferenceEvents.KICKED, () => {
  1370. APP.UI.hideStats();
  1371. APP.UI.notifyKicked();
  1372. // FIXME close
  1373. });
  1374. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1375. APP.store.dispatch(suspendDetected());
  1376. // After wake up, we will be in a state where conference is left
  1377. // there will be dialog shown to user.
  1378. // We do not want video/audio as we show an overlay and after it
  1379. // user need to rejoin or close, while waking up we can detect
  1380. // camera wakeup as a problem with device.
  1381. // We also do not care about device change, which happens
  1382. // on resume after suspending PC.
  1383. if (this.deviceChangeListener)
  1384. JitsiMeetJS.mediaDevices.removeEventListener(
  1385. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1386. this.deviceChangeListener);
  1387. // stop local video
  1388. if (localVideo) {
  1389. localVideo.dispose();
  1390. }
  1391. // stop local audio
  1392. if (localAudio) {
  1393. localAudio.dispose();
  1394. }
  1395. });
  1396. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1397. APP.UI.updateDTMFSupport(isDTMFSupported);
  1398. });
  1399. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1400. // Wait a little bit more just to be sure that we won't miss the
  1401. // extension installation
  1402. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1403. });
  1404. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1405. window.open(
  1406. url, "extension_store_window",
  1407. "resizable,scrollbars=yes,status=1");
  1408. });
  1409. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1410. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1411. if (this.isAudioOnly() && !muted) {
  1412. this._displayAudioOnlyTooltip('videoMute');
  1413. return;
  1414. }
  1415. muteLocalVideo(muted);
  1416. });
  1417. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1418. (stats) => {
  1419. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1420. });
  1421. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1422. (id, stats) => {
  1423. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1424. });
  1425. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1426. APP.UI.initEtherpad(value);
  1427. });
  1428. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1429. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1430. APP.store.dispatch(participantUpdated({
  1431. id: from,
  1432. email: data.value
  1433. }));
  1434. APP.UI.setUserEmail(from, data.value);
  1435. });
  1436. room.addCommandListener(
  1437. this.commands.defaults.AVATAR_URL,
  1438. (data, from) => {
  1439. APP.store.dispatch(
  1440. participantUpdated({
  1441. id: from,
  1442. avatarURL: data.value
  1443. }));
  1444. APP.UI.setUserAvatarUrl(from, data.value);
  1445. });
  1446. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1447. (data, from) => {
  1448. APP.store.dispatch(
  1449. participantUpdated({
  1450. id: from,
  1451. avatarID: data.value
  1452. }));
  1453. APP.UI.setUserAvatarID(from, data.value);
  1454. });
  1455. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1456. this.changeLocalDisplayName.bind(this));
  1457. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1458. (startAudioMuted, startVideoMuted) => {
  1459. room.setStartMutedPolicy({
  1460. audio: startAudioMuted,
  1461. video: startVideoMuted
  1462. });
  1463. }
  1464. );
  1465. room.on(
  1466. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1467. ({ audio, video }) => {
  1468. APP.UI.onStartMutedChanged(audio, video);
  1469. }
  1470. );
  1471. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1472. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1473. && APP.UI.notifyInitiallyMuted();
  1474. });
  1475. room.on(
  1476. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1477. APP.UI.updateDevicesAvailability(id, devices);
  1478. }
  1479. );
  1480. // call hangup
  1481. APP.UI.addListener(UIEvents.HANGUP, () => {
  1482. this.hangup(true);
  1483. });
  1484. // logout
  1485. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1486. AuthHandler.logout(room).then(url => {
  1487. if (url) {
  1488. UIUtil.redirect(url);
  1489. } else {
  1490. this.hangup(true);
  1491. }
  1492. });
  1493. });
  1494. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1495. room.dial(sipNumber)
  1496. .catch((err) => {
  1497. logger.error("Error dialing out", err);
  1498. });
  1499. });
  1500. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1501. (id, oldResolution, newResolution, delay) => {
  1502. var logObject = {
  1503. id: "resolution_change",
  1504. participant: id,
  1505. oldValue: oldResolution,
  1506. newValue: newResolution,
  1507. delay: delay
  1508. };
  1509. room.sendApplicationLog(JSON.stringify(logObject));
  1510. // We only care about the delay between simulcast streams.
  1511. // Longer delays will be caused by something else and will just
  1512. // poison the data.
  1513. if (delay < 2000) {
  1514. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1515. {value: delay});
  1516. }
  1517. });
  1518. // Starts or stops the recording for the conference.
  1519. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1520. room.toggleRecording(options);
  1521. });
  1522. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1523. room.setSubject(topic);
  1524. });
  1525. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1526. APP.UI.setSubject(subject);
  1527. });
  1528. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1529. room.kickParticipant(id);
  1530. });
  1531. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1532. room.muteParticipant(id);
  1533. });
  1534. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1535. AuthHandler.authenticate(room);
  1536. });
  1537. APP.UI.addListener(
  1538. UIEvents.VIDEO_DEVICE_CHANGED,
  1539. (cameraDeviceId) => {
  1540. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1541. createLocalTracks({
  1542. devices: ['video'],
  1543. cameraDeviceId: cameraDeviceId,
  1544. micDeviceId: null
  1545. })
  1546. .then(([stream]) => {
  1547. if (this.isAudioOnly()) {
  1548. return stream.mute()
  1549. .then(() => stream);
  1550. }
  1551. return stream;
  1552. })
  1553. .then(stream => {
  1554. this.useVideoStream(stream);
  1555. logger.log('switched local video device');
  1556. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1557. })
  1558. .catch((err) => {
  1559. APP.UI.showDeviceErrorDialog(null, err);
  1560. });
  1561. }
  1562. );
  1563. APP.UI.addListener(
  1564. UIEvents.AUDIO_DEVICE_CHANGED,
  1565. (micDeviceId) => {
  1566. JitsiMeetJS.analytics.sendEvent(
  1567. 'settings.changeDevice.audioIn');
  1568. createLocalTracks({
  1569. devices: ['audio'],
  1570. cameraDeviceId: null,
  1571. micDeviceId: micDeviceId
  1572. })
  1573. .then(([stream]) => {
  1574. this.useAudioStream(stream);
  1575. logger.log('switched local audio device');
  1576. APP.settings.setMicDeviceId(micDeviceId, true);
  1577. })
  1578. .catch((err) => {
  1579. APP.UI.showDeviceErrorDialog(err, null);
  1580. });
  1581. }
  1582. );
  1583. APP.UI.addListener(
  1584. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1585. (audioOutputDeviceId) => {
  1586. JitsiMeetJS.analytics.sendEvent(
  1587. 'settings.changeDevice.audioOut');
  1588. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1589. .then(() => logger.log('changed audio output device'))
  1590. .catch((err) => {
  1591. logger.warn('Failed to change audio output device. ' +
  1592. 'Default or previously set audio output device ' +
  1593. 'will be used instead.', err);
  1594. });
  1595. }
  1596. );
  1597. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1598. muteLocalVideo(audioOnly);
  1599. // Immediately update the UI by having remote videos and the large
  1600. // video update themselves instead of waiting for some other event
  1601. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1602. // There is no guarantee another event will trigger the update
  1603. // immediately and in all situations, for example because a remote
  1604. // participant is having connection trouble so no status changes.
  1605. APP.UI.updateAllVideos();
  1606. });
  1607. APP.UI.addListener(
  1608. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1609. );
  1610. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1611. (url, state, time, isMuted, volume) => {
  1612. // send start and stop commands once, and remove any updates
  1613. // that had left
  1614. if (state === 'stop' || state === 'start' || state === 'playing') {
  1615. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1616. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1617. value: url,
  1618. attributes: {
  1619. state: state,
  1620. time: time,
  1621. muted: isMuted,
  1622. volume: volume
  1623. }
  1624. });
  1625. }
  1626. else {
  1627. // in case of paused, in order to allow late users to join
  1628. // paused
  1629. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1630. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1631. value: url,
  1632. attributes: {
  1633. state: state,
  1634. time: time,
  1635. muted: isMuted,
  1636. volume: volume
  1637. }
  1638. });
  1639. }
  1640. });
  1641. room.addCommandListener(
  1642. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1643. if (attributes.state === 'stop') {
  1644. APP.UI.onSharedVideoStop(id, attributes);
  1645. }
  1646. else if (attributes.state === 'start') {
  1647. APP.UI.onSharedVideoStart(id, value, attributes);
  1648. }
  1649. else if (attributes.state === 'playing'
  1650. || attributes.state === 'pause') {
  1651. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1652. }
  1653. });
  1654. },
  1655. /**
  1656. * Adds any room listener.
  1657. * @param {string} eventName one of the ConferenceEvents
  1658. * @param {Function} listener the function to be called when the event
  1659. * occurs
  1660. */
  1661. addConferenceListener(eventName, listener) {
  1662. room.on(eventName, listener);
  1663. },
  1664. /**
  1665. * Removes any room listener.
  1666. * @param {string} eventName one of the ConferenceEvents
  1667. * @param {Function} listener the listener to be removed.
  1668. */
  1669. removeConferenceListener(eventName, listener) {
  1670. room.off(eventName, listener);
  1671. },
  1672. /**
  1673. * Inits list of current devices and event listener for device change.
  1674. * @private
  1675. */
  1676. _initDeviceList() {
  1677. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1678. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1679. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1680. // Ugly way to synchronize real device IDs with local
  1681. // storage and settings menu. This is a workaround until
  1682. // getConstraints() method will be implemented in browsers.
  1683. if (localAudio) {
  1684. APP.settings.setMicDeviceId(
  1685. localAudio.getDeviceId(), false);
  1686. }
  1687. if (localVideo) {
  1688. APP.settings.setCameraDeviceId(
  1689. localVideo.getDeviceId(), false);
  1690. }
  1691. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1692. APP.UI.onAvailableDevicesChanged(devices);
  1693. APP.store.dispatch(updateDeviceList(devices));
  1694. });
  1695. this.deviceChangeListener = (devices) =>
  1696. window.setTimeout(
  1697. () => this._onDeviceListChanged(devices), 0);
  1698. JitsiMeetJS.mediaDevices.addEventListener(
  1699. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1700. this.deviceChangeListener);
  1701. }
  1702. },
  1703. /**
  1704. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1705. * handle change of available media devices.
  1706. * @private
  1707. * @param {MediaDeviceInfo[]} devices
  1708. * @returns {Promise}
  1709. */
  1710. _onDeviceListChanged(devices) {
  1711. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1712. // Event handler can be fired before direct
  1713. // enumerateDevices() call, so handle this situation here.
  1714. if (!currentDevices.audioinput &&
  1715. !currentDevices.videoinput &&
  1716. !currentDevices.audiooutput) {
  1717. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1718. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1719. }
  1720. let newDevices =
  1721. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1722. devices, this.isSharingScreen, localVideo, localAudio);
  1723. let promises = [];
  1724. let audioWasMuted = this.audioMuted;
  1725. let videoWasMuted = this.videoMuted;
  1726. let availableAudioInputDevices =
  1727. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1728. let availableVideoInputDevices =
  1729. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1730. if (typeof newDevices.audiooutput !== 'undefined') {
  1731. // Just ignore any errors in catch block.
  1732. promises.push(APP.settings
  1733. .setAudioOutputDeviceId(newDevices.audiooutput)
  1734. .catch());
  1735. }
  1736. promises.push(
  1737. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1738. createLocalTracks,
  1739. newDevices.videoinput,
  1740. newDevices.audioinput)
  1741. .then(tracks =>
  1742. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1743. .then(() => {
  1744. // If audio was muted before, or we unplugged current device
  1745. // and selected new one, then mute new audio track.
  1746. if (audioWasMuted ||
  1747. currentDevices.audioinput.length >
  1748. availableAudioInputDevices.length) {
  1749. muteLocalAudio(true);
  1750. }
  1751. // If video was muted before, or we unplugged current device
  1752. // and selected new one, then mute new video track.
  1753. if (videoWasMuted ||
  1754. currentDevices.videoinput.length >
  1755. availableVideoInputDevices.length) {
  1756. muteLocalVideo(true);
  1757. }
  1758. }));
  1759. return Promise.all(promises)
  1760. .then(() => {
  1761. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1762. APP.UI.onAvailableDevicesChanged(devices);
  1763. });
  1764. },
  1765. /**
  1766. * Toggles the local "raised hand" status.
  1767. */
  1768. maybeToggleRaisedHand() {
  1769. this.setRaisedHand(!this.isHandRaised);
  1770. },
  1771. /**
  1772. * Sets the local "raised hand" status to a particular value.
  1773. */
  1774. setRaisedHand(raisedHand) {
  1775. if (raisedHand !== this.isHandRaised)
  1776. {
  1777. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1778. this.isHandRaised = raisedHand;
  1779. // Advertise the updated status
  1780. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1781. // Update the view
  1782. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1783. }
  1784. },
  1785. /**
  1786. * Log event to callstats and analytics.
  1787. * @param {string} name the event name
  1788. * @param {int} value the value (it's int because google analytics supports
  1789. * only int).
  1790. * @param {string} label short text which provides more info about the event
  1791. * which allows to distinguish between few event cases of the same name
  1792. * NOTE: Should be used after conference.init
  1793. */
  1794. logEvent(name, value, label) {
  1795. if(JitsiMeetJS.analytics) {
  1796. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1797. }
  1798. if(room) {
  1799. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1800. }
  1801. },
  1802. /**
  1803. * Methods logs an application event given in the JSON format.
  1804. * @param {string} logJSON an event to be logged in JSON format
  1805. */
  1806. logJSON(logJSON) {
  1807. if (room) {
  1808. room.sendApplicationLog(logJSON);
  1809. }
  1810. },
  1811. /**
  1812. * Disconnect from the conference and optionally request user feedback.
  1813. * @param {boolean} [requestFeedback=false] if user feedback should be
  1814. * requested
  1815. */
  1816. hangup(requestFeedback = false) {
  1817. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1818. APP.UI.hideRingOverLay();
  1819. let requestFeedbackPromise = requestFeedback
  1820. ? APP.UI.requestFeedbackOnHangup()
  1821. // false - because the thank you dialog shouldn't be displayed
  1822. .catch(() => Promise.resolve(false))
  1823. : Promise.resolve(true);// true - because the thank you dialog
  1824. //should be displayed
  1825. // All promises are returning Promise.resolve to make Promise.all to
  1826. // be resolved when both Promises are finished. Otherwise Promise.all
  1827. // will reject on first rejected Promise and we can redirect the page
  1828. // before all operations are done.
  1829. Promise.all([
  1830. requestFeedbackPromise,
  1831. room.leave().then(disconnect, disconnect)
  1832. ]).then(values => {
  1833. APP.API.notifyReadyToClose();
  1834. maybeRedirectToWelcomePage(values[0]);
  1835. });
  1836. },
  1837. /**
  1838. * Changes the email for the local user
  1839. * @param email {string} the new email
  1840. */
  1841. changeLocalEmail(email = '') {
  1842. email = email.trim();
  1843. if (email === APP.settings.getEmail()) {
  1844. return;
  1845. }
  1846. const localId = room ? room.myUserId() : undefined;
  1847. APP.store.dispatch(participantUpdated({
  1848. id: localId,
  1849. local: true,
  1850. email
  1851. }));
  1852. APP.settings.setEmail(email);
  1853. APP.UI.setUserEmail(localId, email);
  1854. sendData(commands.EMAIL, email);
  1855. },
  1856. /**
  1857. * Changes the avatar url for the local user
  1858. * @param url {string} the new url
  1859. */
  1860. changeLocalAvatarUrl(url = '') {
  1861. url = url.trim();
  1862. if (url === APP.settings.getAvatarUrl()) {
  1863. return;
  1864. }
  1865. const localId = room ? room.myUserId() : undefined;
  1866. APP.store.dispatch(participantUpdated({
  1867. id: localId,
  1868. local: true,
  1869. avatarURL: url
  1870. }));
  1871. APP.settings.setAvatarUrl(url);
  1872. APP.UI.setUserAvatarUrl(localId, url);
  1873. sendData(commands.AVATAR_URL, url);
  1874. },
  1875. /**
  1876. * Sends a message via the data channel.
  1877. * @param {string} to the id of the endpoint that should receive the
  1878. * message. If "" - the message will be sent to all participants.
  1879. * @param {object} payload the payload of the message.
  1880. * @throws NetworkError or InvalidStateError or Error if the operation
  1881. * fails.
  1882. */
  1883. sendEndpointMessage(to, payload) {
  1884. room.sendEndpointMessage(to, payload);
  1885. },
  1886. /**
  1887. * Adds new listener.
  1888. * @param {String} eventName the name of the event
  1889. * @param {Function} listener the listener.
  1890. */
  1891. addListener(eventName, listener) {
  1892. eventEmitter.addListener(eventName, listener);
  1893. },
  1894. /**
  1895. * Removes listener.
  1896. * @param {String} eventName the name of the event that triggers the
  1897. * listener
  1898. * @param {Function} listener the listener.
  1899. */
  1900. removeListener(eventName, listener) {
  1901. eventEmitter.removeListener(eventName, listener);
  1902. },
  1903. /**
  1904. * Checks if the participant given by participantId is currently in the
  1905. * last N set if there's one supported.
  1906. *
  1907. * @param participantId the identifier of the participant
  1908. * @returns {boolean} {true} if the participant given by the participantId
  1909. * is currently in the last N set or if there's no last N set at this point
  1910. * and {false} otherwise
  1911. */
  1912. isInLastN(participantId) {
  1913. return room.isInLastN(participantId);
  1914. },
  1915. /**
  1916. * Changes the display name for the local user
  1917. * @param nickname {string} the new display name
  1918. */
  1919. changeLocalDisplayName(nickname = '') {
  1920. const formattedNickname
  1921. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  1922. if (formattedNickname === APP.settings.getDisplayName()) {
  1923. return;
  1924. }
  1925. APP.store.dispatch(participantUpdated({
  1926. id: this.getMyUserId(),
  1927. local: true,
  1928. name: formattedNickname
  1929. }));
  1930. APP.settings.setDisplayName(formattedNickname);
  1931. if (room) {
  1932. room.setDisplayName(formattedNickname);
  1933. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  1934. }
  1935. }
  1936. };