Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 98KB

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