Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 95KB

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