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

conference.js 96KB

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