Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 95KB

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