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

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