Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 96KB

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