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 84KB

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