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 95KB

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