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 90KB

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