您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 95KB

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