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

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