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

conference.js 94KB

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