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

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