您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 95KB

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