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

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