選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 95KB

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