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

conference.js 101KB

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