Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 96KB

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