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

conference.js 91KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594
  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 * as RemoteControlEvents
  10. from './service/remotecontrol/RemoteControlEvents';
  11. import UIEvents from './service/UI/UIEvents';
  12. import UIUtil from './modules/UI/util/UIUtil';
  13. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  14. import analytics from './modules/analytics/analytics';
  15. import EventEmitter from "events";
  16. import {
  17. AVATAR_ID_COMMAND,
  18. AVATAR_URL_COMMAND,
  19. conferenceFailed,
  20. conferenceJoined,
  21. conferenceLeft,
  22. dataChannelOpened,
  23. toggleAudioOnly,
  24. EMAIL_COMMAND,
  25. lockStateChanged,
  26. p2pStatusChanged
  27. } from './react/features/base/conference';
  28. import { updateDeviceList } from './react/features/base/devices';
  29. import {
  30. isFatalJitsiConnectionError
  31. } from './react/features/base/lib-jitsi-meet';
  32. import {
  33. isVideoMutedByUser,
  34. MEDIA_TYPE,
  35. setAudioAvailable,
  36. setAudioMuted,
  37. setVideoAvailable,
  38. setVideoMuted
  39. } from './react/features/base/media';
  40. import {
  41. localParticipantConnectionStatusChanged,
  42. localParticipantRoleChanged,
  43. MAX_DISPLAY_NAME_LENGTH,
  44. participantConnectionStatusChanged,
  45. participantJoined,
  46. participantLeft,
  47. participantPresenceChanged,
  48. participantRoleChanged,
  49. participantUpdated
  50. } from './react/features/base/participants';
  51. import {
  52. createLocalTracksF,
  53. isLocalTrackMuted,
  54. replaceLocalTrack,
  55. trackAdded,
  56. trackRemoved
  57. } from './react/features/base/tracks';
  58. import { getLocationContextRoot } from './react/features/base/util';
  59. import { statsEmitter } from './react/features/connection-indicator';
  60. import { showDesktopPicker } from './react/features/desktop-picker';
  61. import { maybeOpenFeedbackDialog } from './react/features/feedback';
  62. import { setFilmstripRemoteVideosVisibility } from './react/features/filmstrip';
  63. import {
  64. mediaPermissionPromptVisibilityChanged,
  65. suspendDetected
  66. } from './react/features/overlay';
  67. import {
  68. isButtonEnabled,
  69. showDesktopSharingButton
  70. } from './react/features/toolbox';
  71. const { participantConnectionStatus } = JitsiMeetJS.constants;
  72. const ConnectionEvents = JitsiMeetJS.events.connection;
  73. const ConnectionErrors = JitsiMeetJS.errors.connection;
  74. const ConferenceEvents = JitsiMeetJS.events.conference;
  75. const ConferenceErrors = JitsiMeetJS.errors.conference;
  76. const TrackEvents = JitsiMeetJS.events.track;
  77. const TrackErrors = JitsiMeetJS.errors.track;
  78. const eventEmitter = new EventEmitter();
  79. let room;
  80. let connection;
  81. /*
  82. * Logic to open a desktop picker put on the window global for
  83. * lib-jitsi-meet to detect and invoke
  84. */
  85. window.JitsiMeetScreenObtainer = {
  86. openDesktopPicker(options, onSourceChoose) {
  87. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  88. }
  89. };
  90. /**
  91. * Known custom conference commands.
  92. */
  93. const commands = {
  94. AVATAR_ID: AVATAR_ID_COMMAND,
  95. AVATAR_URL: AVATAR_URL_COMMAND,
  96. CUSTOM_ROLE: "custom-role",
  97. EMAIL: EMAIL_COMMAND,
  98. ETHERPAD: "etherpad",
  99. SHARED_VIDEO: "shared-video"
  100. };
  101. /**
  102. * Open Connection. When authentication failed it shows auth dialog.
  103. * @param roomName the room name to use
  104. * @returns Promise<JitsiConnection>
  105. */
  106. function connect(roomName) {
  107. return openConnection({retry: true, roomName: roomName})
  108. .catch(function (err) {
  109. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  110. APP.UI.notifyTokenAuthFailed();
  111. } else {
  112. APP.UI.notifyConnectionFailed(err);
  113. }
  114. throw err;
  115. });
  116. }
  117. /**
  118. * Share data to other users.
  119. * @param command the command
  120. * @param {string} value new value
  121. */
  122. function sendData(command, value) {
  123. if (!room) {
  124. return;
  125. }
  126. room.removeCommand(command);
  127. room.sendCommand(command, {value: value});
  128. }
  129. /**
  130. * Sets up initially the properties of the local participant - email, avatarID,
  131. * avatarURL, displayName, etc.
  132. */
  133. function _setupLocalParticipantProperties() {
  134. const email = APP.settings.getEmail();
  135. email && sendData(commands.EMAIL, email);
  136. const avatarUrl = APP.settings.getAvatarUrl();
  137. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  138. if (!email && !avatarUrl) {
  139. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  140. }
  141. let nick = APP.settings.getDisplayName();
  142. if (config.useNicks && !nick) {
  143. nick = APP.UI.askForNickname();
  144. APP.settings.setDisplayName(nick);
  145. }
  146. nick && room.setDisplayName(nick);
  147. }
  148. /**
  149. * Get user nickname by user id.
  150. * @param {string} id user id
  151. * @returns {string?} user nickname or undefined if user is unknown.
  152. */
  153. function getDisplayName(id) {
  154. if (APP.conference.isLocalId(id)) {
  155. return APP.settings.getDisplayName();
  156. }
  157. let participant = room.getParticipantById(id);
  158. if (participant && participant.getDisplayName()) {
  159. return participant.getDisplayName();
  160. }
  161. }
  162. /**
  163. * Mute or unmute local audio stream if it exists.
  164. * @param {boolean} muted - if audio stream should be muted or unmuted.
  165. */
  166. function muteLocalAudio(muted) {
  167. APP.store.dispatch(setAudioMuted(muted));
  168. }
  169. /**
  170. * Mute or unmute local video stream if it exists.
  171. * @param {boolean} muted if video stream should be muted or unmuted.
  172. *
  173. */
  174. function muteLocalVideo(muted) {
  175. APP.store.dispatch(setVideoMuted(muted));
  176. }
  177. /**
  178. * Check if the welcome page is enabled and redirects to it.
  179. * If requested show a thank you dialog before that.
  180. * If we have a close page enabled, redirect to it without
  181. * showing any other dialog.
  182. *
  183. * @param {object} options used to decide which particular close page to show
  184. * or if close page is disabled, whether we should show the thankyou dialog
  185. * @param {boolean} options.thankYouDialogVisible - whether we should
  186. * show thank you dialog
  187. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  188. */
  189. function maybeRedirectToWelcomePage(options) {
  190. // if close page is enabled redirect to it, without further action
  191. if (config.enableClosePage) {
  192. const { isGuest } = APP.store.getState()['features/jwt'];
  193. // save whether current user is guest or not, before navigating
  194. // to close page
  195. window.sessionStorage.setItem('guest', isGuest);
  196. assignWindowLocationPathname('static/'
  197. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  198. return;
  199. }
  200. // else: show thankYou dialog only if there is no feedback
  201. if (options.thankYouDialogVisible)
  202. APP.UI.messageHandler.openMessageDialog(
  203. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  204. // if Welcome page is enabled redirect to welcome page after 3 sec.
  205. if (config.enableWelcomePage) {
  206. setTimeout(() => {
  207. APP.settings.setWelcomePageEnabled(true);
  208. assignWindowLocationPathname('./');
  209. }, 3000);
  210. }
  211. }
  212. /**
  213. * Assigns a specific pathname to window.location.pathname taking into account
  214. * the context root of the Web app.
  215. *
  216. * @param {string} pathname - The pathname to assign to
  217. * window.location.pathname. If the specified pathname is relative, the context
  218. * root of the Web app will be prepended to the specified pathname before
  219. * assigning it to window.location.pathname.
  220. * @return {void}
  221. */
  222. function assignWindowLocationPathname(pathname) {
  223. const windowLocation = window.location;
  224. if (!pathname.startsWith('/')) {
  225. // A pathname equal to ./ specifies the current directory. It will be
  226. // fine but pointless to include it because contextRoot is the current
  227. // directory.
  228. pathname.startsWith('./') && (pathname = pathname.substring(2));
  229. pathname = getLocationContextRoot(windowLocation) + pathname;
  230. }
  231. windowLocation.pathname = pathname;
  232. }
  233. class ConferenceConnector {
  234. constructor(resolve, reject) {
  235. this._resolve = resolve;
  236. this._reject = reject;
  237. this.reconnectTimeout = null;
  238. room.on(ConferenceEvents.CONFERENCE_JOINED,
  239. this._handleConferenceJoined.bind(this));
  240. room.on(ConferenceEvents.CONFERENCE_FAILED,
  241. this._onConferenceFailed.bind(this));
  242. room.on(ConferenceEvents.CONFERENCE_ERROR,
  243. this._onConferenceError.bind(this));
  244. }
  245. _handleConferenceFailed(err) {
  246. this._unsubscribe();
  247. this._reject(err);
  248. }
  249. _onConferenceFailed(err, ...params) {
  250. APP.store.dispatch(conferenceFailed(room, err, ...params));
  251. logger.error('CONFERENCE FAILED:', err, ...params);
  252. switch (err) {
  253. case ConferenceErrors.CONNECTION_ERROR:
  254. {
  255. let [msg] = params;
  256. APP.UI.notifyConnectionFailed(msg);
  257. }
  258. break;
  259. case ConferenceErrors.NOT_ALLOWED_ERROR:
  260. {
  261. // let's show some auth not allowed page
  262. assignWindowLocationPathname('static/authError.html');
  263. }
  264. break;
  265. // not enough rights to create conference
  266. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  267. // Schedule reconnect to check if someone else created the room.
  268. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  269. const { password }
  270. = APP.store.getState()['features/base/conference'];
  271. AuthHandler.requireAuth(room, password);
  272. }
  273. break;
  274. case ConferenceErrors.RESERVATION_ERROR:
  275. {
  276. let [code, msg] = params;
  277. APP.UI.notifyReservationError(code, msg);
  278. }
  279. break;
  280. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  281. APP.UI.notifyGracefulShutdown();
  282. break;
  283. case ConferenceErrors.JINGLE_FATAL_ERROR:
  284. APP.UI.notifyInternalError();
  285. break;
  286. case ConferenceErrors.CONFERENCE_DESTROYED:
  287. {
  288. let [reason] = params;
  289. APP.UI.hideStats();
  290. APP.UI.notifyConferenceDestroyed(reason);
  291. }
  292. break;
  293. // FIXME FOCUS_DISCONNECTED is confusing event name.
  294. // What really happens there is that the library is not ready yet,
  295. // because Jicofo is not available, but it is going to give
  296. // it another try.
  297. case ConferenceErrors.FOCUS_DISCONNECTED:
  298. {
  299. let [focus, retrySec] = params;
  300. APP.UI.notifyFocusDisconnected(focus, retrySec);
  301. }
  302. break;
  303. case ConferenceErrors.FOCUS_LEFT:
  304. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  305. // FIXME the conference should be stopped by the library and not by
  306. // the app. Both the errors above are unrecoverable from the library
  307. // perspective.
  308. room.leave().then(() => connection.disconnect());
  309. break;
  310. case ConferenceErrors.CONFERENCE_MAX_USERS:
  311. connection.disconnect();
  312. APP.UI.notifyMaxUsersLimitReached();
  313. break;
  314. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  315. reload();
  316. break;
  317. default:
  318. this._handleConferenceFailed(err, ...params);
  319. }
  320. }
  321. _onConferenceError(err, ...params) {
  322. logger.error('CONFERENCE Error:', err, params);
  323. switch (err) {
  324. case ConferenceErrors.CHAT_ERROR:
  325. {
  326. let [code, msg] = params;
  327. APP.UI.showChatError(code, msg);
  328. }
  329. break;
  330. default:
  331. logger.error("Unknown error.", err);
  332. }
  333. }
  334. _unsubscribe() {
  335. room.off(
  336. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  337. room.off(
  338. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  339. if (this.reconnectTimeout !== null) {
  340. clearTimeout(this.reconnectTimeout);
  341. }
  342. AuthHandler.closeAuth();
  343. }
  344. _handleConferenceJoined() {
  345. this._unsubscribe();
  346. this._resolve();
  347. }
  348. connect() {
  349. room.join();
  350. }
  351. }
  352. /**
  353. * Disconnects the connection.
  354. * @returns resolved Promise. We need this in order to make the Promise.all
  355. * call in hangup() to resolve when all operations are finished.
  356. */
  357. function disconnect() {
  358. connection.disconnect();
  359. APP.API.notifyConferenceLeft(APP.conference.roomName);
  360. return Promise.resolve();
  361. }
  362. /**
  363. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  364. *
  365. * @param {JitsiMeetJS.connection.error} error - The reported error.
  366. * @returns {void}
  367. * @private
  368. */
  369. function _connectionFailedHandler(error) {
  370. if (isFatalJitsiConnectionError(error)) {
  371. APP.connection.removeEventListener(
  372. ConnectionEvents.CONNECTION_FAILED,
  373. _connectionFailedHandler);
  374. if (room)
  375. room.leave();
  376. }
  377. }
  378. export default {
  379. /**
  380. * Flag used to delay modification of the muted status of local media tracks
  381. * until those are created (or not, but at that point it's certain that
  382. * the tracks won't exist).
  383. */
  384. _localTracksInitialized: false,
  385. isModerator: false,
  386. isSharingScreen: false,
  387. /**
  388. * Indicates if the desktop sharing functionality has been enabled.
  389. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  390. * as well as the status returned by
  391. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  392. * either if the desktop sharing is not supported by the current browser
  393. * or if it was disabled through lib-jitsi-meet specific options (check
  394. * config.js for listed options).
  395. */
  396. isDesktopSharingEnabled: false,
  397. /**
  398. * Set to <tt>true</tt> if the desktop sharing functionality has been
  399. * explicitly disabled in the config.
  400. */
  401. isDesktopSharingDisabledByConfig: false,
  402. /**
  403. * The text displayed when the desktop sharing button is disabled through
  404. * the config. The value is set through
  405. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  406. */
  407. desktopSharingDisabledTooltip: null,
  408. /*
  409. * Whether the local "raisedHand" flag is on.
  410. */
  411. isHandRaised: false,
  412. /*
  413. * Whether the local participant is the dominant speaker in the conference.
  414. */
  415. isDominantSpeaker: false,
  416. /**
  417. * The local audio track (if any).
  418. * FIXME tracks from redux store should be the single source of truth
  419. * @type {JitsiLocalTrack|null}
  420. */
  421. localAudio: null,
  422. /**
  423. * The local video track (if any).
  424. * FIXME tracks from redux store should be the single source of truth, but
  425. * more refactoring is required around screen sharing ('localVideo' usages).
  426. * @type {JitsiLocalTrack|null}
  427. */
  428. localVideo: null,
  429. /**
  430. * Creates local media tracks and connects to a room. Will show error
  431. * dialogs in case accessing the local microphone and/or camera failed. Will
  432. * show guidance overlay for users on how to give access to camera and/or
  433. * microphone.
  434. * @param {string} roomName
  435. * @param {object} options
  436. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  437. * only audio track will be created and the audio only mode will be turned
  438. * on.
  439. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  440. * should start with screensharing instead of camera video.
  441. * @param {boolean} options.startWithAudioMuted - will start the conference
  442. * without any audio tracks.
  443. * @param {boolean} options.startWithVideoMuted - will start the conference
  444. * without any video tracks.
  445. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  446. */
  447. createInitialLocalTracksAndConnect(roomName, options = {}) {
  448. let audioAndVideoError,
  449. audioOnlyError,
  450. screenSharingError,
  451. videoOnlyError;
  452. const initialDevices = [];
  453. let requestedAudio = false;
  454. let requestedVideo = false;
  455. if (!options.startWithAudioMuted) {
  456. initialDevices.push('audio');
  457. requestedAudio = true;
  458. }
  459. if (!options.startWithVideoMuted
  460. && !options.startAudioOnly
  461. && !options.startScreenSharing) {
  462. initialDevices.push('video');
  463. requestedVideo = true;
  464. }
  465. JitsiMeetJS.mediaDevices.addEventListener(
  466. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  467. browser =>
  468. APP.store.dispatch(
  469. mediaPermissionPromptVisibilityChanged(true, browser))
  470. );
  471. let tryCreateLocalTracks;
  472. // Enable audio only mode
  473. if (config.startAudioOnly) {
  474. APP.store.dispatch(toggleAudioOnly());
  475. }
  476. // FIXME is there any simpler way to rewrite this spaghetti below ?
  477. if (options.startScreenSharing) {
  478. tryCreateLocalTracks = this._createDesktopTrack()
  479. .then(desktopStream => {
  480. if (!requestedAudio) {
  481. return [desktopStream];
  482. }
  483. return createLocalTracksF({ devices: ['audio'] }, true)
  484. .then(([audioStream]) => {
  485. return [desktopStream, audioStream];
  486. })
  487. .catch(error => {
  488. audioOnlyError = error;
  489. return [desktopStream];
  490. });
  491. }).catch(error => {
  492. logger.error('Failed to obtain desktop stream', error);
  493. screenSharingError = error;
  494. return requestedAudio
  495. ? createLocalTracksF({ devices: ['audio'] }, true)
  496. : [];
  497. }).catch(error => {
  498. audioOnlyError = error;
  499. return [];
  500. });
  501. } else if (!requestedAudio && !requestedVideo) {
  502. // Resolve with no tracks
  503. tryCreateLocalTracks = Promise.resolve([]);
  504. } else {
  505. tryCreateLocalTracks = createLocalTracksF(
  506. { devices: initialDevices }, true)
  507. .catch(err => {
  508. if (requestedAudio && requestedVideo) {
  509. // Try audio only...
  510. audioAndVideoError = err;
  511. return createLocalTracksF({devices: ['audio']}, true);
  512. } else if (requestedAudio && !requestedVideo) {
  513. audioOnlyError = err;
  514. return [];
  515. } else if (requestedVideo && !requestedAudio) {
  516. videoOnlyError = err;
  517. return [];
  518. }
  519. logger.error('Should never happen');
  520. }).catch(err => {
  521. // Log this just in case...
  522. if (!requestedAudio) {
  523. logger.error('The impossible just happened', err);
  524. }
  525. audioOnlyError = err;
  526. // Try video only...
  527. return requestedVideo
  528. ? createLocalTracksF({devices: ['video']}, true)
  529. : [];
  530. })
  531. .catch(err => {
  532. // Log this just in case...
  533. if (!requestedVideo) {
  534. logger.error('The impossible just happened', err);
  535. }
  536. videoOnlyError = err;
  537. return [];
  538. });
  539. }
  540. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  541. .then(([tracks, con]) => {
  542. APP.store.dispatch(
  543. mediaPermissionPromptVisibilityChanged(false));
  544. // FIXME If there will be microphone error it will cover any
  545. // screensharing dialog, but it's still better than in
  546. // the reverse order where the screensharing dialog will
  547. // sometimes be closing the microphone alert ($.prompt.close();
  548. // is called). Need to figure out dialogs chaining to fix that.
  549. if (screenSharingError) {
  550. this._handleScreenSharingError(screenSharingError);
  551. }
  552. if (audioAndVideoError || audioOnlyError) {
  553. if (audioOnlyError || videoOnlyError) {
  554. // If both requests for 'audio' + 'video' and 'audio'
  555. // only failed, we assume that there are some problems
  556. // with user's microphone and show corresponding dialog.
  557. APP.UI.showMicErrorNotification(audioOnlyError);
  558. APP.UI.showCameraErrorNotification(videoOnlyError);
  559. } else {
  560. // If request for 'audio' + 'video' failed, but request
  561. // for 'audio' only was OK, we assume that we had
  562. // problems with camera and show corresponding dialog.
  563. APP.UI.showCameraErrorNotification(audioAndVideoError);
  564. }
  565. }
  566. return [tracks, con];
  567. });
  568. },
  569. /**
  570. * Open new connection and join to the conference.
  571. * @param {object} options
  572. * @param {string} roomName name of the conference
  573. * @returns {Promise}
  574. */
  575. init(options) {
  576. this.roomName = options.roomName;
  577. // attaches global error handler, if there is already one, respect it
  578. if (JitsiMeetJS.getGlobalOnErrorHandler){
  579. var oldOnErrorHandler = window.onerror;
  580. window.onerror = function (message, source, lineno, colno, error) {
  581. JitsiMeetJS.getGlobalOnErrorHandler(
  582. message, source, lineno, colno, error);
  583. if (oldOnErrorHandler)
  584. oldOnErrorHandler(message, source, lineno, colno, error);
  585. };
  586. var oldOnUnhandledRejection = window.onunhandledrejection;
  587. window.onunhandledrejection = function(event) {
  588. JitsiMeetJS.getGlobalOnErrorHandler(
  589. null, null, null, null, event.reason);
  590. if (oldOnUnhandledRejection)
  591. oldOnUnhandledRejection(event);
  592. };
  593. }
  594. return JitsiMeetJS.init(
  595. Object.assign(
  596. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  597. ).then(() => {
  598. analytics.init();
  599. return this.createInitialLocalTracksAndConnect(
  600. options.roomName, {
  601. startAudioOnly: config.startAudioOnly,
  602. startScreenSharing: config.startScreenSharing,
  603. startWithAudioMuted: config.startWithAudioMuted,
  604. startWithVideoMuted: config.startWithVideoMuted,
  605. });
  606. }).then(([tracks, con]) => {
  607. tracks.forEach(track => {
  608. if (track.isAudioTrack() && this.isLocalAudioMuted()) {
  609. track.mute();
  610. } else if (track.isVideoTrack()
  611. && this.isLocalVideoMuted()) {
  612. track.mute();
  613. }
  614. });
  615. logger.log('initialized with %s local tracks', tracks.length);
  616. this._localTracksInitialized = true;
  617. con.addEventListener(
  618. ConnectionEvents.CONNECTION_FAILED,
  619. _connectionFailedHandler);
  620. APP.connection = connection = con;
  621. // Desktop sharing related stuff:
  622. this.isDesktopSharingDisabledByConfig
  623. = config.disableDesktopSharing;
  624. this.isDesktopSharingEnabled
  625. = !this.isDesktopSharingDisabledByConfig
  626. && JitsiMeetJS.isDesktopSharingEnabled();
  627. this.desktopSharingDisabledTooltip
  628. = interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP;
  629. eventEmitter.emit(
  630. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  631. this.isDesktopSharingEnabled);
  632. APP.store.dispatch(showDesktopSharingButton());
  633. this._createRoom(tracks);
  634. APP.remoteControl.init();
  635. if (isButtonEnabled('contacts')
  636. && !interfaceConfig.filmStripOnly) {
  637. APP.UI.ContactList = new ContactList(room);
  638. }
  639. // if user didn't give access to mic or camera or doesn't have
  640. // them at all, we mark corresponding toolbar buttons as muted,
  641. // so that the user can try unmute later on and add audio/video
  642. // to the conference
  643. if (!tracks.find((t) => t.isAudioTrack())) {
  644. this.setAudioMuteStatus(true);
  645. }
  646. if (!tracks.find((t) => t.isVideoTrack())) {
  647. this.setVideoMuteStatus(true);
  648. }
  649. this._initDeviceList();
  650. if (config.iAmRecorder)
  651. this.recorder = new Recorder();
  652. // XXX The API will take care of disconnecting from the XMPP
  653. // server (and, thus, leaving the room) on unload.
  654. return new Promise((resolve, reject) => {
  655. (new ConferenceConnector(resolve, reject)).connect();
  656. });
  657. });
  658. },
  659. /**
  660. * Check if id is id of the local user.
  661. * @param {string} id id to check
  662. * @returns {boolean}
  663. */
  664. isLocalId(id) {
  665. return this.getMyUserId() === id;
  666. },
  667. /**
  668. * Tells whether the local video is muted or not.
  669. * @return {boolean}
  670. */
  671. isLocalVideoMuted() {
  672. // If the tracks are not ready, read from base/media state
  673. return this._localTracksInitialized
  674. ? isLocalTrackMuted(
  675. APP.store.getState()['features/base/tracks'],
  676. MEDIA_TYPE.VIDEO)
  677. : isVideoMutedByUser(APP.store);
  678. },
  679. /**
  680. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  681. * @param {boolean} mute true for mute and false for unmute.
  682. * @param {boolean} [showUI] when set to false will not display any error
  683. * dialogs in case of media permissions error.
  684. */
  685. muteAudio(mute, showUI = true) {
  686. // Not ready to modify track's state yet
  687. if (!this._localTracksInitialized) {
  688. // This will only modify base/media.audio.muted which is then synced
  689. // up with the track at the end of local tracks initialization.
  690. muteLocalAudio(mute);
  691. this.setAudioMuteStatus(mute);
  692. return;
  693. } else if (this.isLocalAudioMuted() === mute) {
  694. // NO-OP
  695. return;
  696. }
  697. if (!this.localAudio && !mute) {
  698. const maybeShowErrorDialog = error => {
  699. showUI && APP.UI.showMicErrorNotification(error);
  700. };
  701. createLocalTracksF({ devices: ['audio'] }, false)
  702. .then(([audioTrack]) => audioTrack)
  703. .catch(error => {
  704. maybeShowErrorDialog(error);
  705. // Rollback the audio muted status by using null track
  706. return null;
  707. })
  708. .then(audioTrack => this.useAudioStream(audioTrack));
  709. } else {
  710. muteLocalAudio(mute);
  711. }
  712. },
  713. /**
  714. * Returns whether local audio is muted or not.
  715. * @returns {boolean}
  716. */
  717. isLocalAudioMuted() {
  718. // If the tracks are not ready, read from base/media state
  719. return this._localTracksInitialized
  720. ? isLocalTrackMuted(
  721. APP.store.getState()['features/base/tracks'],
  722. MEDIA_TYPE.AUDIO)
  723. : Boolean(
  724. APP.store.getState()['features/base/media'].audio.muted);
  725. },
  726. /**
  727. * Simulates toolbar button click for audio mute. Used by shortcuts
  728. * and API.
  729. * @param {boolean} [showUI] when set to false will not display any error
  730. * dialogs in case of media permissions error.
  731. */
  732. toggleAudioMuted(showUI = true) {
  733. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  734. },
  735. /**
  736. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  737. * @param mute true for mute and false for unmute.
  738. * @param {boolean} [showUI] when set to false will not display any error
  739. * dialogs in case of media permissions error.
  740. */
  741. muteVideo(mute, showUI = true) {
  742. // If not ready to modify track's state yet adjust the base/media
  743. if (!this._localTracksInitialized) {
  744. // This will only modify base/media.video.muted which is then synced
  745. // up with the track at the end of local tracks initialization.
  746. muteLocalVideo(mute);
  747. this.setVideoMuteStatus(mute);
  748. return;
  749. } else if (this.isLocalVideoMuted() === mute) {
  750. // NO-OP
  751. return;
  752. }
  753. // FIXME it is possible to queue this task twice, but it's not causing
  754. // any issues. Specifically this can happen when the previous
  755. // get user media call is blocked on "ask user for permissions" dialog.
  756. if (!this.localVideo && !mute) {
  757. const maybeShowErrorDialog = error => {
  758. showUI && APP.UI.showCameraErrorNotification(error);
  759. };
  760. // Try to create local video if there wasn't any.
  761. // This handles the case when user joined with no video
  762. // (dismissed screen sharing screen or in audio only mode), but
  763. // decided to add it later on by clicking on muted video icon or
  764. // turning off the audio only mode.
  765. //
  766. // FIXME when local track creation is moved to react/redux
  767. // it should take care of the use case described above
  768. createLocalTracksF({ devices: ['video'] }, false)
  769. .then(([videoTrack]) => videoTrack)
  770. .catch(error => {
  771. // FIXME should send some feedback to the API on error ?
  772. maybeShowErrorDialog(error);
  773. // Rollback the video muted status by using null track
  774. return null;
  775. })
  776. .then(videoTrack => this.useVideoStream(videoTrack));
  777. } else {
  778. // FIXME show error dialog if it fails (should be handled by react)
  779. muteLocalVideo(mute);
  780. }
  781. },
  782. /**
  783. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  784. * @param {boolean} [showUI] when set to false will not display any error
  785. * dialogs in case of media permissions error.
  786. */
  787. toggleVideoMuted(showUI = true) {
  788. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  789. },
  790. /**
  791. * Retrieve list of conference participants (without local user).
  792. * @returns {JitsiParticipant[]}
  793. */
  794. listMembers() {
  795. return room.getParticipants();
  796. },
  797. /**
  798. * Retrieve list of ids of conference participants (without local user).
  799. * @returns {string[]}
  800. */
  801. listMembersIds() {
  802. return room.getParticipants().map(p => p.getId());
  803. },
  804. /**
  805. * Checks whether the participant identified by id is a moderator.
  806. * @id id to search for participant
  807. * @return {boolean} whether the participant is moderator
  808. */
  809. isParticipantModerator(id) {
  810. let user = room.getParticipantById(id);
  811. return user && user.isModerator();
  812. },
  813. /**
  814. * Check if SIP is supported.
  815. * @returns {boolean}
  816. */
  817. sipGatewayEnabled() {
  818. return room.isSIPCallingSupported();
  819. },
  820. get membersCount() {
  821. return room.getParticipants().length + 1;
  822. },
  823. /**
  824. * Returns true if the callstats integration is enabled, otherwise returns
  825. * false.
  826. *
  827. * @returns true if the callstats integration is enabled, otherwise returns
  828. * false.
  829. */
  830. isCallstatsEnabled() {
  831. return room && room.isCallstatsEnabled();
  832. },
  833. /**
  834. * Sends the given feedback through CallStats if enabled.
  835. *
  836. * @param overallFeedback an integer between 1 and 5 indicating the
  837. * user feedback
  838. * @param detailedFeedback detailed feedback from the user. Not yet used
  839. */
  840. sendFeedback(overallFeedback, detailedFeedback) {
  841. return room.sendFeedback (overallFeedback, detailedFeedback);
  842. },
  843. /**
  844. * Get speaker stats that track total dominant speaker time.
  845. *
  846. * @returns {object} A hash with keys being user ids and values being the
  847. * library's SpeakerStats model used for calculating time as dominant
  848. * speaker.
  849. */
  850. getSpeakerStats() {
  851. return room.getSpeakerStats();
  852. },
  853. /**
  854. * Returns the connection times stored in the library.
  855. */
  856. getConnectionTimes() {
  857. return this._room.getConnectionTimes();
  858. },
  859. // used by torture currently
  860. isJoined() {
  861. return this._room
  862. && this._room.isJoined();
  863. },
  864. getConnectionState() {
  865. return this._room
  866. && this._room.getConnectionState();
  867. },
  868. /**
  869. * Obtains current P2P ICE connection state.
  870. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  871. * P2P connection
  872. */
  873. getP2PConnectionState() {
  874. return this._room
  875. && this._room.getP2PConnectionState();
  876. },
  877. /**
  878. * Starts P2P (for tests only)
  879. * @private
  880. */
  881. _startP2P() {
  882. try {
  883. this._room && this._room.startP2PSession();
  884. } catch (error) {
  885. logger.error("Start P2P failed", error);
  886. throw error;
  887. }
  888. },
  889. /**
  890. * Stops P2P (for tests only)
  891. * @private
  892. */
  893. _stopP2P() {
  894. try {
  895. this._room && this._room.stopP2PSession();
  896. } catch (error) {
  897. logger.error("Stop P2P failed", error);
  898. throw error;
  899. }
  900. },
  901. /**
  902. * Checks whether or not our connection is currently in interrupted and
  903. * reconnect attempts are in progress.
  904. *
  905. * @returns {boolean} true if the connection is in interrupted state or
  906. * false otherwise.
  907. */
  908. isConnectionInterrupted() {
  909. return this._room.isConnectionInterrupted();
  910. },
  911. /**
  912. * Finds JitsiParticipant for given id.
  913. *
  914. * @param {string} id participant's identifier(MUC nickname).
  915. *
  916. * @returns {JitsiParticipant|null} participant instance for given id or
  917. * null if not found.
  918. */
  919. getParticipantById(id) {
  920. return room ? room.getParticipantById(id) : null;
  921. },
  922. /**
  923. * Get participant connection status for the participant.
  924. *
  925. * @param {string} id participant's identifier(MUC nickname)
  926. *
  927. * @returns {ParticipantConnectionStatus|null} the status of the participant
  928. * or null if no such participant is found or participant is the local user.
  929. */
  930. getParticipantConnectionStatus(id) {
  931. let participant = this.getParticipantById(id);
  932. return participant ? participant.getConnectionStatus() : null;
  933. },
  934. /**
  935. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  936. * the given <tt>id</tt>.
  937. *
  938. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  939. *
  940. * @return {string} the participant's display name or the default string if
  941. * absent.
  942. */
  943. getParticipantDisplayName(id) {
  944. let displayName = getDisplayName(id);
  945. if (displayName) {
  946. return displayName;
  947. } else {
  948. if (APP.conference.isLocalId(id)) {
  949. return APP.translation.generateTranslationHTML(
  950. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  951. } else {
  952. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  953. }
  954. }
  955. },
  956. getMyUserId() {
  957. return this._room
  958. && this._room.myUserId();
  959. },
  960. /**
  961. * Indicates if recording is supported in this conference.
  962. */
  963. isRecordingSupported() {
  964. return this._room && this._room.isRecordingSupported();
  965. },
  966. /**
  967. * Returns the recording state or undefined if the room is not defined.
  968. */
  969. getRecordingState() {
  970. return (this._room) ? this._room.getRecordingState() : undefined;
  971. },
  972. /**
  973. * Will be filled with values only when config.debug is enabled.
  974. * Its used by torture to check audio levels.
  975. */
  976. audioLevelsMap: {},
  977. /**
  978. * Returns the stored audio level (stored only if config.debug is enabled)
  979. * @param id the id for the user audio level to return (the id value is
  980. * returned for the participant using getMyUserId() method)
  981. */
  982. getPeerSSRCAudioLevel(id) {
  983. return this.audioLevelsMap[id];
  984. },
  985. /**
  986. * @return {number} the number of participants in the conference with at
  987. * least one track.
  988. */
  989. getNumberOfParticipantsWithTracks() {
  990. return this._room.getParticipants()
  991. .filter((p) => p.getTracks().length > 0)
  992. .length;
  993. },
  994. /**
  995. * Returns the stats.
  996. */
  997. getStats() {
  998. return room.connectionQuality.getStats();
  999. },
  1000. // end used by torture
  1001. getLogs() {
  1002. return room.getLogs();
  1003. },
  1004. /**
  1005. * Download logs, a function that can be called from console while
  1006. * debugging.
  1007. * @param filename (optional) specify target filename
  1008. */
  1009. saveLogs(filename = 'meetlog.json') {
  1010. // this can be called from console and will not have reference to this
  1011. // that's why we reference the global var
  1012. let logs = APP.conference.getLogs();
  1013. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1014. let elem = document.createElement('a');
  1015. elem.download = filename;
  1016. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  1017. elem.dataset.downloadurl
  1018. = ['text/json', elem.download, elem.href].join(':');
  1019. elem.dispatchEvent(new MouseEvent('click', {
  1020. view: window,
  1021. bubbles: true,
  1022. cancelable: false
  1023. }));
  1024. },
  1025. /**
  1026. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1027. * desire to keep room private to this instance and (2) the need of other
  1028. * modules to send and receive commands to and from participants.
  1029. * Eventually, this instance remains in control with respect to the
  1030. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1031. * JitsiConference) is to be used in the implementation of the Command(s)
  1032. * API of this instance.
  1033. */
  1034. commands: {
  1035. /**
  1036. * Known custom conference commands.
  1037. */
  1038. defaults: commands,
  1039. /**
  1040. * Receives notifications from other participants about commands aka
  1041. * custom events (sent by sendCommand or sendCommandOnce methods).
  1042. * @param command {String} the name of the command
  1043. * @param handler {Function} handler for the command
  1044. */
  1045. addCommandListener () {
  1046. room.addCommandListener.apply(room, arguments);
  1047. },
  1048. /**
  1049. * Removes command.
  1050. * @param name {String} the name of the command.
  1051. */
  1052. removeCommand () {
  1053. room.removeCommand.apply(room, arguments);
  1054. },
  1055. /**
  1056. * Sends command.
  1057. * @param name {String} the name of the command.
  1058. * @param values {Object} with keys and values that will be sent.
  1059. */
  1060. sendCommand () {
  1061. room.sendCommand.apply(room, arguments);
  1062. },
  1063. /**
  1064. * Sends command one time.
  1065. * @param name {String} the name of the command.
  1066. * @param values {Object} with keys and values that will be sent.
  1067. */
  1068. sendCommandOnce () {
  1069. room.sendCommandOnce.apply(room, arguments);
  1070. }
  1071. },
  1072. _createRoom (localTracks) {
  1073. room = connection.initJitsiConference(APP.conference.roomName,
  1074. this._getConferenceOptions());
  1075. this._setLocalAudioVideoStreams(localTracks);
  1076. this._room = room; // FIXME do not use this
  1077. _setupLocalParticipantProperties();
  1078. this._setupListeners();
  1079. },
  1080. /**
  1081. * Sets local video and audio streams.
  1082. * @param {JitsiLocalTrack[]} tracks=[]
  1083. * @returns {Promise[]}
  1084. * @private
  1085. */
  1086. _setLocalAudioVideoStreams(tracks = []) {
  1087. return tracks.map(track => {
  1088. if (track.isAudioTrack()) {
  1089. return this.useAudioStream(track);
  1090. } else if (track.isVideoTrack()) {
  1091. return this.useVideoStream(track);
  1092. } else {
  1093. logger.error(
  1094. "Ignored not an audio nor a video track: ", track);
  1095. return Promise.resolve();
  1096. }
  1097. });
  1098. },
  1099. _getConferenceOptions() {
  1100. let options = config;
  1101. if (config.enableRecording && !config.recordingType) {
  1102. options.recordingType = (config.hosts &&
  1103. (typeof config.hosts.jirecon != "undefined"))?
  1104. "jirecon" : "colibri";
  1105. }
  1106. return options;
  1107. },
  1108. /**
  1109. * Start using provided video stream.
  1110. * Stops previous video stream.
  1111. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1112. * @returns {Promise}
  1113. */
  1114. useVideoStream(newStream) {
  1115. return APP.store.dispatch(
  1116. replaceLocalTrack(this.localVideo, newStream, room))
  1117. .then(() => {
  1118. this.localVideo = newStream;
  1119. if (newStream) {
  1120. this.isSharingScreen = newStream.videoType === 'desktop';
  1121. APP.UI.addLocalStream(newStream);
  1122. } else {
  1123. this.isSharingScreen = false;
  1124. }
  1125. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1126. APP.UI.updateDesktopSharingButtons();
  1127. });
  1128. },
  1129. /**
  1130. * Start using provided audio stream.
  1131. * Stops previous audio stream.
  1132. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1133. * @returns {Promise}
  1134. */
  1135. useAudioStream(newStream) {
  1136. return APP.store.dispatch(
  1137. replaceLocalTrack(this.localAudio, newStream, room))
  1138. .then(() => {
  1139. this.localAudio = newStream;
  1140. if (newStream) {
  1141. APP.UI.addLocalStream(newStream);
  1142. }
  1143. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1144. });
  1145. },
  1146. /**
  1147. * Triggers a tooltip to display when a feature was attempted to be used
  1148. * while in audio only mode.
  1149. *
  1150. * @param {string} featureName - The name of the feature that attempted to
  1151. * toggle.
  1152. * @private
  1153. * @returns {void}
  1154. */
  1155. _displayAudioOnlyTooltip(featureName) {
  1156. let buttonName = null;
  1157. let tooltipElementId = null;
  1158. switch (featureName) {
  1159. case 'screenShare':
  1160. buttonName = 'desktop';
  1161. tooltipElementId = 'screenshareWhileAudioOnly';
  1162. break;
  1163. case 'videoMute':
  1164. buttonName = 'camera';
  1165. tooltipElementId = 'unmuteWhileAudioOnly';
  1166. break;
  1167. }
  1168. if (tooltipElementId) {
  1169. APP.UI.showToolbar(6000);
  1170. APP.UI.showCustomToolbarPopup(
  1171. buttonName, tooltipElementId, true, 5000);
  1172. }
  1173. },
  1174. /**
  1175. * Returns whether or not the conference is currently in audio only mode.
  1176. *
  1177. * @returns {boolean}
  1178. */
  1179. isAudioOnly() {
  1180. return Boolean(
  1181. APP.store.getState()['features/base/conference'].audioOnly);
  1182. },
  1183. videoSwitchInProgress: false,
  1184. /**
  1185. * This fields stores a handler which will create a Promise which turns off
  1186. * the screen sharing and restores the previous video state (was there
  1187. * any video, before switching to screen sharing ? was it muted ?).
  1188. *
  1189. * Once called this fields is cleared to <tt>null</tt>.
  1190. * @type {Function|null}
  1191. */
  1192. _untoggleScreenSharing: null,
  1193. /**
  1194. * Creates a Promise which turns off the screen sharing and restores
  1195. * the previous state described by the arguments.
  1196. *
  1197. * This method is bound to the appropriate values, after switching to screen
  1198. * sharing and stored in {@link _untoggleScreenSharing}.
  1199. *
  1200. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1201. * used, before switching to screen sharing.
  1202. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1203. * switching to screen sharing.
  1204. * @return {Promise} resolved after the screen sharing is turned off, or
  1205. * rejected with some error (no idea what kind of error, possible GUM error)
  1206. * in case it fails.
  1207. * @private
  1208. */
  1209. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1210. this._untoggleScreenSharing = null;
  1211. this.videoSwitchInProgress = true;
  1212. APP.remoteControl.receiver.stop();
  1213. let promise = null;
  1214. if (didHaveVideo) {
  1215. promise = createLocalTracksF({ devices: ['video'] })
  1216. .then(([stream]) => this.useVideoStream(stream))
  1217. .then(() => {
  1218. JitsiMeetJS.analytics.sendEvent(
  1219. 'conference.sharingDesktop.stop');
  1220. logger.log('switched back to local video');
  1221. if (!this.localVideo && wasVideoMuted) {
  1222. return Promise.reject('No local video to be muted!');
  1223. } else if (wasVideoMuted && this.localVideo) {
  1224. return this.localVideo.mute();
  1225. }
  1226. })
  1227. .catch(error => {
  1228. logger.error('failed to switch back to local video', error);
  1229. return this.useVideoStream(null).then(() => {
  1230. // Still fail with the original err
  1231. return Promise.reject(error);
  1232. });
  1233. });
  1234. } else {
  1235. promise = this.useVideoStream(null);
  1236. }
  1237. return promise.then(
  1238. () => {
  1239. this.videoSwitchInProgress = false;
  1240. },
  1241. error => {
  1242. this.videoSwitchInProgress = false;
  1243. throw error;
  1244. });
  1245. },
  1246. /**
  1247. * Toggles between screen sharing and camera video if the toggle parameter
  1248. * is not specified and starts the procedure for obtaining new screen
  1249. * sharing/video track otherwise.
  1250. *
  1251. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1252. * obtained. If false - new video track will be obtain. If not specified -
  1253. * toggles between screen sharing and camera video.
  1254. * @param {Object} [options] - Screen sharing options that will be passed to
  1255. * createLocalTracks.
  1256. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1257. * sources that have to be displayed in the desktop picker window ('screen',
  1258. * 'window', etc.).
  1259. * @return {Promise.<T>}
  1260. */
  1261. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1262. if (this.videoSwitchInProgress) {
  1263. return Promise.reject('Switch in progress.');
  1264. }
  1265. if (!this.isDesktopSharingEnabled) {
  1266. return Promise.reject(
  1267. 'Cannot toggle screen sharing: not supported.');
  1268. }
  1269. if (this.isAudioOnly()) {
  1270. this._displayAudioOnlyTooltip('screenShare');
  1271. return Promise.reject('No screensharing in audio only mode');
  1272. }
  1273. if (toggle) {
  1274. return this._switchToScreenSharing(options);
  1275. } else {
  1276. return this._untoggleScreenSharing();
  1277. }
  1278. },
  1279. /**
  1280. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1281. * @param {Object} [options] - Screen sharing options that will be passed to
  1282. * createLocalTracks.
  1283. *
  1284. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1285. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1286. * {@link JitsiTrackError}.
  1287. *
  1288. * @private
  1289. */
  1290. _createDesktopTrack(options = {}) {
  1291. let externalInstallation = false;
  1292. let DSExternalInstallationInProgress = false;
  1293. const didHaveVideo = Boolean(this.localVideo);
  1294. const wasVideoMuted = this.isLocalVideoMuted();
  1295. return createLocalTracksF({
  1296. desktopSharingSources: options.desktopSharingSources,
  1297. devices: ['desktop'],
  1298. desktopSharingExtensionExternalInstallation: {
  1299. interval: 500,
  1300. checkAgain: () => DSExternalInstallationInProgress,
  1301. listener: (status, url) => {
  1302. switch(status) {
  1303. case "waitingForExtension": {
  1304. DSExternalInstallationInProgress = true;
  1305. externalInstallation = true;
  1306. const listener = () => {
  1307. // Wait a little bit more just to be sure that we
  1308. // won't miss the extension installation
  1309. setTimeout(
  1310. () => {
  1311. DSExternalInstallationInProgress = false;
  1312. },
  1313. 500);
  1314. APP.UI.removeListener(
  1315. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1316. listener);
  1317. };
  1318. APP.UI.addListener(
  1319. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1320. listener);
  1321. APP.UI.showExtensionExternalInstallationDialog(url);
  1322. break;
  1323. }
  1324. case "extensionFound":
  1325. // Close the dialog.
  1326. externalInstallation && $.prompt.close();
  1327. break;
  1328. default:
  1329. // Unknown status
  1330. }
  1331. }
  1332. }
  1333. }).then(([desktopStream]) => {
  1334. // Stores the "untoggle" handler which remembers whether was
  1335. // there any video before and whether was it muted.
  1336. this._untoggleScreenSharing
  1337. = this._turnScreenSharingOff
  1338. .bind(this, didHaveVideo, wasVideoMuted);
  1339. desktopStream.on(
  1340. TrackEvents.LOCAL_TRACK_STOPPED,
  1341. () => {
  1342. // If the stream was stopped during screen sharing
  1343. // session then we should switch back to video.
  1344. this.isSharingScreen
  1345. && this._untoggleScreenSharing
  1346. && this._untoggleScreenSharing();
  1347. }
  1348. );
  1349. // close external installation dialog on success.
  1350. externalInstallation && $.prompt.close();
  1351. return desktopStream;
  1352. }, error => {
  1353. DSExternalInstallationInProgress = false;
  1354. // close external installation dialog on success.
  1355. externalInstallation && $.prompt.close();
  1356. throw error;
  1357. });
  1358. },
  1359. /**
  1360. * Tries to switch to the screenshairng mode by disposing camera stream and
  1361. * replacing it with a desktop one.
  1362. *
  1363. * @param {Object} [options] - Screen sharing options that will be passed to
  1364. * createLocalTracks.
  1365. *
  1366. * @return {Promise} - A Promise resolved if the operation succeeds or
  1367. * rejected with some unknown type of error in case it fails. Promise will
  1368. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1369. *
  1370. * @private
  1371. */
  1372. _switchToScreenSharing(options = {}) {
  1373. if (this.videoSwitchInProgress) {
  1374. return Promise.reject('Switch in progress.');
  1375. }
  1376. this.videoSwitchInProgress = true;
  1377. return this._createDesktopTrack(options).then(stream => {
  1378. return this.useVideoStream(stream);
  1379. }).then(() => {
  1380. this.videoSwitchInProgress = false;
  1381. JitsiMeetJS.analytics.sendEvent('conference.sharingDesktop.start');
  1382. logger.log('sharing local desktop');
  1383. }).catch(error => {
  1384. this.videoSwitchInProgress = false;
  1385. // Pawel: With this call I'm trying to preserve the original
  1386. // behaviour although it is not clear why would we "untoggle"
  1387. // on failure. I suppose it was to restore video in case there
  1388. // was some problem during "this.useVideoStream(desktopStream)".
  1389. // It's important to note that the handler will not be available
  1390. // if we fail early on trying to get desktop media (which makes
  1391. // sense, because the camera video is still being used, so
  1392. // nothing to "untoggle").
  1393. if (this._untoggleScreenSharing) {
  1394. this._untoggleScreenSharing();
  1395. }
  1396. // FIXME the code inside of _handleScreenSharingError is
  1397. // asynchronous, but does not return a Promise and is not part of
  1398. // the current Promise chain.
  1399. this._handleScreenSharingError(error);
  1400. return Promise.reject(error);
  1401. });
  1402. },
  1403. /**
  1404. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1405. * trying to create screensharing track. It will either do nothing if
  1406. * the dialog was canceled on user's request or display inline installation
  1407. * dialog and ask the user to install the extension, once the extension is
  1408. * installed it will switch the conference to screensharing. The last option
  1409. * is that an unrecoverable error dialog will be displayed.
  1410. * @param {JitsiTrackError} error - The error returned by
  1411. * {@link _createDesktopTrack} Promise.
  1412. * @private
  1413. */
  1414. _handleScreenSharingError(error) {
  1415. if (error.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1416. return;
  1417. }
  1418. logger.error('failed to share local desktop', error);
  1419. if (error.name === TrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1420. // If start with screen sharing the extension will fail to install
  1421. // (if not found), because the request has been triggered by the
  1422. // script. Show a dialog which asks user to click "install" and try
  1423. // again switching to the screen sharing.
  1424. APP.UI.showExtensionInlineInstallationDialog(
  1425. () => {
  1426. this.toggleScreenSharing().catch(() => {});
  1427. }
  1428. );
  1429. return;
  1430. } else if (error.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1431. APP.UI.showExtensionRequiredDialog(
  1432. config.desktopSharingFirefoxExtensionURL
  1433. );
  1434. return;
  1435. }
  1436. // Handling:
  1437. // TrackErrors.PERMISSION_DENIED
  1438. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1439. // TrackErrors.GENERAL
  1440. // and any other
  1441. let dialogTxt;
  1442. let dialogTitleKey;
  1443. if (error.name === TrackErrors.PERMISSION_DENIED) {
  1444. dialogTxt = APP.translation.generateTranslationHTML(
  1445. "dialog.screenSharingPermissionDeniedError");
  1446. dialogTitleKey = "dialog.error";
  1447. } else {
  1448. dialogTxt = APP.translation.generateTranslationHTML(
  1449. "dialog.failtoinstall");
  1450. dialogTitleKey = "dialog.permissionDenied";
  1451. }
  1452. APP.UI.messageHandler.openDialog(dialogTitleKey, dialogTxt, false);
  1453. },
  1454. /**
  1455. * Setup interaction between conference and UI.
  1456. */
  1457. _setupListeners() {
  1458. // add local streams when joined to the conference
  1459. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1460. APP.store.dispatch(conferenceJoined(room));
  1461. APP.UI.mucJoined();
  1462. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1463. APP.UI.markVideoInterrupted(false);
  1464. });
  1465. room.on(
  1466. ConferenceEvents.CONFERENCE_LEFT,
  1467. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1468. room.on(
  1469. ConferenceEvents.AUTH_STATUS_CHANGED,
  1470. (authEnabled, authLogin) =>
  1471. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1472. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1473. user => APP.UI.onUserFeaturesChanged(user));
  1474. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1475. if (user.isHidden())
  1476. return;
  1477. APP.store.dispatch(participantJoined({
  1478. id,
  1479. name: user.getDisplayName(),
  1480. role: user.getRole()
  1481. }));
  1482. logger.log('USER %s connnected', id, user);
  1483. APP.API.notifyUserJoined(id);
  1484. APP.UI.addUser(user);
  1485. // check the roles for the new user and reflect them
  1486. APP.UI.updateUserRole(user);
  1487. updateRemoteThumbnailsVisibility();
  1488. });
  1489. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1490. APP.store.dispatch(participantLeft(id, user));
  1491. logger.log('USER %s LEFT', id, user);
  1492. APP.API.notifyUserLeft(id);
  1493. APP.UI.removeUser(id, user.getDisplayName());
  1494. APP.UI.onSharedVideoStop(id);
  1495. updateRemoteThumbnailsVisibility();
  1496. });
  1497. room.on(ConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1498. APP.store.dispatch(participantPresenceChanged(id, status));
  1499. let user = room.getParticipantById(id);
  1500. if (user) {
  1501. APP.UI.updateUserStatus(user, status);
  1502. }
  1503. });
  1504. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1505. if (this.isLocalId(id)) {
  1506. logger.info(`My role changed, new role: ${role}`);
  1507. APP.store.dispatch(localParticipantRoleChanged(role));
  1508. if (this.isModerator !== room.isModerator()) {
  1509. this.isModerator = room.isModerator();
  1510. APP.UI.updateLocalRole(room.isModerator());
  1511. }
  1512. } else {
  1513. APP.store.dispatch(participantRoleChanged(id, role));
  1514. let user = room.getParticipantById(id);
  1515. if (user) {
  1516. APP.UI.updateUserRole(user);
  1517. }
  1518. }
  1519. });
  1520. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1521. if (!track || track.isLocal())
  1522. return;
  1523. APP.store.dispatch(trackAdded(track));
  1524. });
  1525. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1526. if (!track || track.isLocal())
  1527. return;
  1528. APP.store.dispatch(trackRemoved(track));
  1529. });
  1530. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1531. if (this.isLocalId(id)
  1532. && this.localAudio && this.localAudio.isMuted()) {
  1533. lvl = 0;
  1534. }
  1535. if (config.debug) {
  1536. this.audioLevelsMap[id] = lvl;
  1537. if (config.debugAudioLevels)
  1538. logger.log("AudioLevel:" + id + "/" + lvl);
  1539. }
  1540. APP.UI.setAudioLevel(id, lvl);
  1541. });
  1542. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1543. APP.UI.showToolbar(6000);
  1544. APP.UI.showCustomToolbarPopup(
  1545. 'microphone', 'talkWhileMutedPopup', true, 5000);
  1546. });
  1547. room.on(
  1548. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1549. (leavingIds, enteringIds) => {
  1550. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1551. });
  1552. room.on(
  1553. ConferenceEvents.P2P_STATUS,
  1554. (jitsiConference, p2p) => {
  1555. APP.store.dispatch(p2pStatusChanged(p2p));
  1556. });
  1557. room.on(
  1558. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1559. (id, connectionStatus) => {
  1560. APP.store.dispatch(participantConnectionStatusChanged(
  1561. id, connectionStatus));
  1562. APP.UI.participantConnectionStatusChanged(id);
  1563. });
  1564. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1565. if (this.isLocalId(id)) {
  1566. this.isDominantSpeaker = true;
  1567. this.setRaisedHand(false);
  1568. } else {
  1569. this.isDominantSpeaker = false;
  1570. var participant = room.getParticipantById(id);
  1571. if (participant) {
  1572. APP.UI.setRaisedHandStatus(participant, false);
  1573. }
  1574. }
  1575. APP.UI.markDominantSpeaker(id);
  1576. });
  1577. if (!interfaceConfig.filmStripOnly) {
  1578. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1579. APP.UI.markVideoInterrupted(true);
  1580. });
  1581. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1582. APP.UI.markVideoInterrupted(false);
  1583. });
  1584. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1585. let nick = getDisplayName(id);
  1586. APP.API.notifyReceivedChatMessage({
  1587. id,
  1588. nick,
  1589. body,
  1590. ts
  1591. });
  1592. APP.UI.addMessage(id, nick, body, ts);
  1593. });
  1594. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1595. APP.API.notifySendingChatMessage(message);
  1596. room.sendTextMessage(message);
  1597. });
  1598. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1599. try {
  1600. // do not try to select participant if there is none (we
  1601. // are alone in the room), otherwise an error will be
  1602. // thrown cause reporting mechanism is not available
  1603. // (datachannels currently)
  1604. if (room.getParticipants().length === 0)
  1605. return;
  1606. room.selectParticipant(id);
  1607. } catch (e) {
  1608. JitsiMeetJS.analytics.sendEvent(
  1609. 'selectParticipant.failed');
  1610. reportError(e);
  1611. }
  1612. });
  1613. APP.UI.addListener(
  1614. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1615. () => this._displayAudioOnlyTooltip('videoMute'));
  1616. APP.UI.addListener(
  1617. UIEvents.PINNED_ENDPOINT,
  1618. updateRemoteThumbnailsVisibility);
  1619. }
  1620. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1621. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1622. participantConnectionStatus.INTERRUPTED));
  1623. APP.UI.showLocalConnectionInterrupted(true);
  1624. });
  1625. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1626. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1627. participantConnectionStatus.ACTIVE));
  1628. APP.UI.showLocalConnectionInterrupted(false);
  1629. });
  1630. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1631. const formattedDisplayName
  1632. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1633. APP.store.dispatch(participantUpdated({
  1634. id,
  1635. name: formattedDisplayName
  1636. }));
  1637. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1638. APP.UI.changeDisplayName(id, formattedDisplayName);
  1639. });
  1640. room.on(
  1641. ConferenceEvents.LOCK_STATE_CHANGED,
  1642. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1643. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1644. room.setLocalParticipantProperty(
  1645. "remoteControlSessionStatus",
  1646. isActive
  1647. );
  1648. APP.UI.setLocalRemoteControlActiveChanged();
  1649. });
  1650. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1651. (participant, name, oldValue, newValue) => {
  1652. switch (name) {
  1653. case 'raisedHand':
  1654. APP.UI.setRaisedHandStatus(participant, newValue);
  1655. break;
  1656. case 'remoteControlSessionStatus':
  1657. APP.UI.setRemoteControlActiveStatus(
  1658. participant.getId(),
  1659. newValue);
  1660. break;
  1661. default:
  1662. // ignore
  1663. }
  1664. });
  1665. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1666. logger.log("Received recorder status change: ", status, error);
  1667. APP.UI.updateRecordingState(status);
  1668. });
  1669. room.on(ConferenceEvents.KICKED, () => {
  1670. APP.UI.hideStats();
  1671. APP.UI.notifyKicked();
  1672. // FIXME close
  1673. });
  1674. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1675. APP.store.dispatch(suspendDetected());
  1676. // After wake up, we will be in a state where conference is left
  1677. // there will be dialog shown to user.
  1678. // We do not want video/audio as we show an overlay and after it
  1679. // user need to rejoin or close, while waking up we can detect
  1680. // camera wakeup as a problem with device.
  1681. // We also do not care about device change, which happens
  1682. // on resume after suspending PC.
  1683. if (this.deviceChangeListener)
  1684. JitsiMeetJS.mediaDevices.removeEventListener(
  1685. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1686. this.deviceChangeListener);
  1687. // stop local video
  1688. if (this.localVideo) {
  1689. this.localVideo.dispose();
  1690. this.localVideo = null;
  1691. }
  1692. // stop local audio
  1693. if (this.localAudio) {
  1694. this.localAudio.dispose();
  1695. this.localAudio = null;
  1696. }
  1697. });
  1698. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1699. APP.UI.updateDTMFSupport(isDTMFSupported);
  1700. });
  1701. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1702. this.muteAudio(muted);
  1703. });
  1704. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1705. if (this.isAudioOnly() && !muted) {
  1706. this._displayAudioOnlyTooltip('videoMute');
  1707. } else {
  1708. this.muteVideo(muted);
  1709. }
  1710. });
  1711. statsEmitter.startListeningForStats(room);
  1712. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1713. APP.UI.initEtherpad(value);
  1714. });
  1715. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1716. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1717. APP.store.dispatch(participantUpdated({
  1718. id: from,
  1719. email: data.value
  1720. }));
  1721. APP.UI.setUserEmail(from, data.value);
  1722. });
  1723. room.addCommandListener(
  1724. this.commands.defaults.AVATAR_URL,
  1725. (data, from) => {
  1726. APP.store.dispatch(
  1727. participantUpdated({
  1728. id: from,
  1729. avatarURL: data.value
  1730. }));
  1731. APP.UI.setUserAvatarUrl(from, data.value);
  1732. });
  1733. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1734. (data, from) => {
  1735. APP.store.dispatch(
  1736. participantUpdated({
  1737. id: from,
  1738. avatarID: data.value
  1739. }));
  1740. APP.UI.setUserAvatarID(from, data.value);
  1741. });
  1742. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1743. this.changeLocalDisplayName.bind(this));
  1744. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1745. (startAudioMuted, startVideoMuted) => {
  1746. room.setStartMutedPolicy({
  1747. audio: startAudioMuted,
  1748. video: startVideoMuted
  1749. });
  1750. }
  1751. );
  1752. room.on(
  1753. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1754. ({ audio, video }) => {
  1755. APP.UI.onStartMutedChanged(audio, video);
  1756. }
  1757. );
  1758. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1759. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1760. && APP.UI.notifyInitiallyMuted();
  1761. });
  1762. room.on(
  1763. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1764. APP.UI.updateDevicesAvailability(id, devices);
  1765. }
  1766. );
  1767. room.on(
  1768. ConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1769. APP.store.dispatch(dataChannelOpened());
  1770. }
  1771. );
  1772. // call hangup
  1773. APP.UI.addListener(UIEvents.HANGUP, () => {
  1774. this.hangup(true);
  1775. });
  1776. // logout
  1777. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1778. AuthHandler.logout(room).then(url => {
  1779. if (url) {
  1780. UIUtil.redirect(url);
  1781. } else {
  1782. this.hangup(true);
  1783. }
  1784. });
  1785. });
  1786. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1787. (id, oldResolution, newResolution, delay) => {
  1788. var logObject = {
  1789. id: "resolution_change",
  1790. participant: id,
  1791. oldValue: oldResolution,
  1792. newValue: newResolution,
  1793. delay: delay
  1794. };
  1795. room.sendApplicationLog(JSON.stringify(logObject));
  1796. // We only care about the delay between simulcast streams.
  1797. // Longer delays will be caused by something else and will just
  1798. // poison the data.
  1799. if (delay < 2000) {
  1800. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1801. {value: delay});
  1802. }
  1803. });
  1804. // Starts or stops the recording for the conference.
  1805. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1806. room.toggleRecording(options);
  1807. });
  1808. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1809. room.setSubject(topic);
  1810. });
  1811. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1812. APP.UI.setSubject(subject);
  1813. });
  1814. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1815. room.kickParticipant(id);
  1816. });
  1817. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1818. room.muteParticipant(id);
  1819. });
  1820. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1821. AuthHandler.authenticate(room);
  1822. });
  1823. APP.UI.addListener(
  1824. UIEvents.VIDEO_DEVICE_CHANGED,
  1825. (cameraDeviceId) => {
  1826. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1827. createLocalTracksF({
  1828. devices: ['video'],
  1829. cameraDeviceId: cameraDeviceId,
  1830. micDeviceId: null
  1831. })
  1832. .then(([stream]) => {
  1833. if (this.isAudioOnly()) {
  1834. return stream.mute()
  1835. .then(() => stream);
  1836. }
  1837. return stream;
  1838. })
  1839. .then(stream => {
  1840. this.useVideoStream(stream);
  1841. logger.log('switched local video device');
  1842. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1843. })
  1844. .catch((err) => {
  1845. APP.UI.showCameraErrorNotification(err);
  1846. });
  1847. }
  1848. );
  1849. APP.UI.addListener(
  1850. UIEvents.AUDIO_DEVICE_CHANGED,
  1851. (micDeviceId) => {
  1852. JitsiMeetJS.analytics.sendEvent(
  1853. 'settings.changeDevice.audioIn');
  1854. createLocalTracksF({
  1855. devices: ['audio'],
  1856. cameraDeviceId: null,
  1857. micDeviceId: micDeviceId
  1858. })
  1859. .then(([stream]) => {
  1860. this.useAudioStream(stream);
  1861. logger.log('switched local audio device');
  1862. APP.settings.setMicDeviceId(micDeviceId, true);
  1863. })
  1864. .catch((err) => {
  1865. APP.UI.showMicErrorNotification(err);
  1866. });
  1867. }
  1868. );
  1869. APP.UI.addListener(
  1870. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1871. (audioOutputDeviceId) => {
  1872. JitsiMeetJS.analytics.sendEvent(
  1873. 'settings.changeDevice.audioOut');
  1874. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1875. .then(() => logger.log('changed audio output device'))
  1876. .catch((err) => {
  1877. logger.warn('Failed to change audio output device. ' +
  1878. 'Default or previously set audio output device ' +
  1879. 'will be used instead.', err);
  1880. });
  1881. }
  1882. );
  1883. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1884. // FIXME On web video track is stored both in redux and in
  1885. // 'localVideo' field, video is attempted to be unmuted twice when
  1886. // turning off the audio only mode. This will crash the app with
  1887. // 'unmute operation is already in progress'.
  1888. // Because there's no logic in redux about creating new track in
  1889. // case unmute when not track exists the things have to go through
  1890. // muteVideo logic in such case.
  1891. const tracks = APP.store.getState()['features/base/tracks'];
  1892. const isTrackInRedux
  1893. = Boolean(
  1894. tracks.find(
  1895. track => track.jitsiTrack
  1896. && track.jitsiTrack.getType() === 'video'));
  1897. if (!isTrackInRedux) {
  1898. this.muteVideo(audioOnly);
  1899. }
  1900. // Immediately update the UI by having remote videos and the large
  1901. // video update themselves instead of waiting for some other event
  1902. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1903. // There is no guarantee another event will trigger the update
  1904. // immediately and in all situations, for example because a remote
  1905. // participant is having connection trouble so no status changes.
  1906. APP.UI.updateAllVideos();
  1907. });
  1908. APP.UI.addListener(
  1909. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1910. );
  1911. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1912. (url, state, time, isMuted, volume) => {
  1913. // send start and stop commands once, and remove any updates
  1914. // that had left
  1915. if (state === 'stop' || state === 'start' || state === 'playing') {
  1916. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1917. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1918. value: url,
  1919. attributes: {
  1920. state: state,
  1921. time: time,
  1922. muted: isMuted,
  1923. volume: volume
  1924. }
  1925. });
  1926. }
  1927. else {
  1928. // in case of paused, in order to allow late users to join
  1929. // paused
  1930. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1931. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1932. value: url,
  1933. attributes: {
  1934. state: state,
  1935. time: time,
  1936. muted: isMuted,
  1937. volume: volume
  1938. }
  1939. });
  1940. }
  1941. updateRemoteThumbnailsVisibility();
  1942. });
  1943. room.addCommandListener(
  1944. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1945. if (attributes.state === 'stop') {
  1946. APP.UI.onSharedVideoStop(id, attributes);
  1947. }
  1948. else if (attributes.state === 'start') {
  1949. APP.UI.onSharedVideoStart(id, value, attributes);
  1950. }
  1951. else if (attributes.state === 'playing'
  1952. || attributes.state === 'pause') {
  1953. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1954. }
  1955. });
  1956. function updateRemoteThumbnailsVisibility() {
  1957. const localUserId = APP.conference.getMyUserId();
  1958. const remoteParticipantsCount = room.getParticipantCount() - 1;
  1959. // Get the remote thumbnail count for cases where there are
  1960. // non-participants displaying video, such as with video sharing.
  1961. const remoteVideosCount = APP.UI.getRemoteVideosCount();
  1962. const shouldShowRemoteThumbnails = interfaceConfig.filmStripOnly
  1963. || (APP.UI.isPinned(localUserId) && remoteVideosCount)
  1964. || remoteVideosCount > 1
  1965. || remoteParticipantsCount !== remoteVideosCount;
  1966. APP.store.dispatch(
  1967. setFilmstripRemoteVideosVisibility(
  1968. Boolean(shouldShowRemoteThumbnails)));
  1969. }
  1970. },
  1971. /**
  1972. * Adds any room listener.
  1973. * @param {string} eventName one of the ConferenceEvents
  1974. * @param {Function} listener the function to be called when the event
  1975. * occurs
  1976. */
  1977. addConferenceListener(eventName, listener) {
  1978. room.on(eventName, listener);
  1979. },
  1980. /**
  1981. * Removes any room listener.
  1982. * @param {string} eventName one of the ConferenceEvents
  1983. * @param {Function} listener the listener to be removed.
  1984. */
  1985. removeConferenceListener(eventName, listener) {
  1986. room.off(eventName, listener);
  1987. },
  1988. /**
  1989. * Inits list of current devices and event listener for device change.
  1990. * @private
  1991. */
  1992. _initDeviceList() {
  1993. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  1994. .then(isDeviceListAvailable => {
  1995. if (isDeviceListAvailable
  1996. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1997. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1998. // Ugly way to synchronize real device IDs with local
  1999. // storage and settings menu. This is a workaround until
  2000. // getConstraints() method will be implemented
  2001. // in browsers.
  2002. if (this.localAudio) {
  2003. APP.settings.setMicDeviceId(
  2004. this.localAudio.getDeviceId(), false);
  2005. }
  2006. if (this.localVideo) {
  2007. APP.settings.setCameraDeviceId(
  2008. this.localVideo.getDeviceId(), false);
  2009. }
  2010. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2011. APP.UI.onAvailableDevicesChanged(devices);
  2012. APP.store.dispatch(updateDeviceList(devices));
  2013. });
  2014. this.deviceChangeListener = (devices) =>
  2015. window.setTimeout(
  2016. () => this._onDeviceListChanged(devices), 0);
  2017. JitsiMeetJS.mediaDevices.addEventListener(
  2018. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  2019. this.deviceChangeListener);
  2020. }
  2021. })
  2022. .catch((error) => {
  2023. logger.warn(`Error getting device list: ${error}`);
  2024. });
  2025. },
  2026. /**
  2027. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2028. * handle change of available media devices.
  2029. * @private
  2030. * @param {MediaDeviceInfo[]} devices
  2031. * @returns {Promise}
  2032. */
  2033. _onDeviceListChanged(devices) {
  2034. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2035. // Event handler can be fired before direct
  2036. // enumerateDevices() call, so handle this situation here.
  2037. if (!currentDevices.audioinput &&
  2038. !currentDevices.videoinput &&
  2039. !currentDevices.audiooutput) {
  2040. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2041. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2042. }
  2043. let newDevices =
  2044. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2045. devices,
  2046. this.isSharingScreen,
  2047. this.localVideo,
  2048. this.localAudio);
  2049. let promises = [];
  2050. let audioWasMuted = this.isLocalAudioMuted();
  2051. let videoWasMuted = this.isLocalVideoMuted();
  2052. let availableAudioInputDevices =
  2053. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  2054. let availableVideoInputDevices =
  2055. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  2056. if (typeof newDevices.audiooutput !== 'undefined') {
  2057. // Just ignore any errors in catch block.
  2058. promises.push(APP.settings
  2059. .setAudioOutputDeviceId(newDevices.audiooutput)
  2060. .catch());
  2061. }
  2062. promises.push(
  2063. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2064. createLocalTracksF,
  2065. newDevices.videoinput,
  2066. newDevices.audioinput)
  2067. .then(tracks =>
  2068. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  2069. .then(() => {
  2070. // If audio was muted before, or we unplugged current device
  2071. // and selected new one, then mute new audio track.
  2072. if (audioWasMuted ||
  2073. currentDevices.audioinput.length >
  2074. availableAudioInputDevices.length) {
  2075. muteLocalAudio(true);
  2076. }
  2077. // If video was muted before, or we unplugged current device
  2078. // and selected new one, then mute new video track.
  2079. if (!this.isSharingScreen &&
  2080. (videoWasMuted ||
  2081. currentDevices.videoinput.length >
  2082. availableVideoInputDevices.length)) {
  2083. muteLocalVideo(true);
  2084. }
  2085. }));
  2086. return Promise.all(promises)
  2087. .then(() => {
  2088. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2089. APP.UI.onAvailableDevicesChanged(devices);
  2090. });
  2091. },
  2092. /**
  2093. * Determines whether or not the audio button should be enabled.
  2094. */
  2095. updateAudioIconEnabled() {
  2096. const audioMediaDevices
  2097. = mediaDeviceHelper.getCurrentMediaDevices().audioinput;
  2098. const audioDeviceCount
  2099. = audioMediaDevices ? audioMediaDevices.length : 0;
  2100. // The audio functionality is considered available if there are any
  2101. // audio devices detected or if the local audio stream already exists.
  2102. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2103. logger.debug(
  2104. 'Microphone button enabled: ' + available,
  2105. 'local audio: ' + this.localAudio,
  2106. 'audio devices: ' + audioMediaDevices,
  2107. 'device count: ' + audioDeviceCount);
  2108. APP.store.dispatch(setAudioAvailable(available));
  2109. APP.API.notifyAudioAvailabilityChanged(available);
  2110. },
  2111. /**
  2112. * Determines whether or not the video button should be enabled.
  2113. */
  2114. updateVideoIconEnabled() {
  2115. const videoMediaDevices
  2116. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  2117. const videoDeviceCount
  2118. = videoMediaDevices ? videoMediaDevices.length : 0;
  2119. // The video functionality is considered available if there are any
  2120. // video devices detected or if there is local video stream already
  2121. // active which could be either screensharing stream or a video track
  2122. // created before the permissions were rejected (through browser
  2123. // config).
  2124. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2125. logger.debug(
  2126. 'Camera button enabled: ' + available,
  2127. 'local video: ' + this.localVideo,
  2128. 'video devices: ' + videoMediaDevices,
  2129. 'device count: ' + videoDeviceCount);
  2130. APP.store.dispatch(setVideoAvailable(available));
  2131. APP.API.notifyVideoAvailabilityChanged(available);
  2132. },
  2133. /**
  2134. * Toggles the local "raised hand" status.
  2135. */
  2136. maybeToggleRaisedHand() {
  2137. this.setRaisedHand(!this.isHandRaised);
  2138. },
  2139. /**
  2140. * Sets the local "raised hand" status to a particular value.
  2141. */
  2142. setRaisedHand(raisedHand) {
  2143. if (raisedHand !== this.isHandRaised)
  2144. {
  2145. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2146. this.isHandRaised = raisedHand;
  2147. // Advertise the updated status
  2148. room.setLocalParticipantProperty("raisedHand", raisedHand);
  2149. // Update the view
  2150. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2151. }
  2152. },
  2153. /**
  2154. * Log event to callstats and analytics.
  2155. * @param {string} name the event name
  2156. * @param {int} value the value (it's int because google analytics supports
  2157. * only int).
  2158. * @param {string} label short text which provides more info about the event
  2159. * which allows to distinguish between few event cases of the same name
  2160. * NOTE: Should be used after conference.init
  2161. */
  2162. logEvent(name, value, label) {
  2163. if (JitsiMeetJS.analytics) {
  2164. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  2165. }
  2166. if (room) {
  2167. room.sendApplicationLog(JSON.stringify({name, value, label}));
  2168. }
  2169. },
  2170. /**
  2171. * Methods logs an application event given in the JSON format.
  2172. * @param {string} logJSON an event to be logged in JSON format
  2173. */
  2174. logJSON(logJSON) {
  2175. if (room) {
  2176. room.sendApplicationLog(logJSON);
  2177. }
  2178. },
  2179. /**
  2180. * Disconnect from the conference and optionally request user feedback.
  2181. * @param {boolean} [requestFeedback=false] if user feedback should be
  2182. * requested
  2183. */
  2184. hangup(requestFeedback = false) {
  2185. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2186. let requestFeedbackPromise;
  2187. if (requestFeedback) {
  2188. requestFeedbackPromise
  2189. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2190. // false because the thank you dialog shouldn't be displayed
  2191. .catch(() => Promise.resolve(false));
  2192. } else {
  2193. requestFeedbackPromise = Promise.resolve(true);
  2194. }
  2195. // All promises are returning Promise.resolve to make Promise.all to
  2196. // be resolved when both Promises are finished. Otherwise Promise.all
  2197. // will reject on first rejected Promise and we can redirect the page
  2198. // before all operations are done.
  2199. Promise.all([
  2200. requestFeedbackPromise,
  2201. room.leave().then(disconnect, disconnect)
  2202. ]).then(values => {
  2203. APP.API.notifyReadyToClose();
  2204. maybeRedirectToWelcomePage(values[0]);
  2205. });
  2206. },
  2207. /**
  2208. * Changes the email for the local user
  2209. * @param email {string} the new email
  2210. */
  2211. changeLocalEmail(email = '') {
  2212. email = String(email).trim();
  2213. if (email === APP.settings.getEmail()) {
  2214. return;
  2215. }
  2216. const localId = room ? room.myUserId() : undefined;
  2217. APP.store.dispatch(participantUpdated({
  2218. id: localId,
  2219. local: true,
  2220. email
  2221. }));
  2222. APP.settings.setEmail(email);
  2223. APP.UI.setUserEmail(localId, email);
  2224. sendData(commands.EMAIL, email);
  2225. },
  2226. /**
  2227. * Changes the avatar url for the local user
  2228. * @param url {string} the new url
  2229. */
  2230. changeLocalAvatarUrl(url = '') {
  2231. url = String(url).trim();
  2232. if (url === APP.settings.getAvatarUrl()) {
  2233. return;
  2234. }
  2235. const localId = room ? room.myUserId() : undefined;
  2236. APP.store.dispatch(participantUpdated({
  2237. id: localId,
  2238. local: true,
  2239. avatarURL: url
  2240. }));
  2241. APP.settings.setAvatarUrl(url);
  2242. APP.UI.setUserAvatarUrl(localId, url);
  2243. sendData(commands.AVATAR_URL, url);
  2244. },
  2245. /**
  2246. * Sends a message via the data channel.
  2247. * @param {string} to the id of the endpoint that should receive the
  2248. * message. If "" - the message will be sent to all participants.
  2249. * @param {object} payload the payload of the message.
  2250. * @throws NetworkError or InvalidStateError or Error if the operation
  2251. * fails.
  2252. */
  2253. sendEndpointMessage(to, payload) {
  2254. room.sendEndpointMessage(to, payload);
  2255. },
  2256. /**
  2257. * Adds new listener.
  2258. * @param {String} eventName the name of the event
  2259. * @param {Function} listener the listener.
  2260. */
  2261. addListener(eventName, listener) {
  2262. eventEmitter.addListener(eventName, listener);
  2263. },
  2264. /**
  2265. * Removes listener.
  2266. * @param {String} eventName the name of the event that triggers the
  2267. * listener
  2268. * @param {Function} listener the listener.
  2269. */
  2270. removeListener(eventName, listener) {
  2271. eventEmitter.removeListener(eventName, listener);
  2272. },
  2273. /**
  2274. * Changes the display name for the local user
  2275. * @param nickname {string} the new display name
  2276. */
  2277. changeLocalDisplayName(nickname = '') {
  2278. const formattedNickname
  2279. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2280. if (formattedNickname === APP.settings.getDisplayName()) {
  2281. return;
  2282. }
  2283. APP.store.dispatch(participantUpdated({
  2284. id: this.getMyUserId(),
  2285. local: true,
  2286. name: formattedNickname
  2287. }));
  2288. APP.settings.setDisplayName(formattedNickname);
  2289. if (room) {
  2290. room.setDisplayName(formattedNickname);
  2291. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  2292. }
  2293. },
  2294. /**
  2295. * Returns the desktop sharing source id or undefined if the desktop sharing
  2296. * is not active at the moment.
  2297. *
  2298. * @returns {string|undefined} - The source id. If the track is not desktop
  2299. * track or the source id is not available, undefined will be returned.
  2300. */
  2301. getDesktopSharingSourceId() {
  2302. return this.localVideo.sourceId;
  2303. },
  2304. /**
  2305. * Returns the desktop sharing source type or undefined if the desktop
  2306. * sharing is not active at the moment.
  2307. *
  2308. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2309. * not desktop track or the source type is not available, undefined will be
  2310. * returned.
  2311. */
  2312. getDesktopSharingSourceType() {
  2313. return this.localVideo.sourceType;
  2314. },
  2315. /**
  2316. * Sets the video muted status.
  2317. *
  2318. * @param {boolean} muted - New muted status.
  2319. */
  2320. setVideoMuteStatus(muted) {
  2321. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2322. APP.API.notifyVideoMutedStatusChanged(muted);
  2323. },
  2324. /**
  2325. * Sets the audio muted status.
  2326. *
  2327. * @param {boolean} muted - New muted status.
  2328. */
  2329. setAudioMuteStatus(muted) {
  2330. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2331. APP.API.notifyAudioMutedStatusChanged(muted);
  2332. }
  2333. };