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

conference.js 104KB

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