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.

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