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

conference.js 106KB

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