Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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