You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 103KB

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