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

conference.js 83KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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: () => DSExternalInstallationInProgress,
  1153. listener: (status, url) => {
  1154. switch(status) {
  1155. case "waitingForExtension": {
  1156. DSExternalInstallationInProgress = true;
  1157. externalInstallation = true;
  1158. const listener = () => {
  1159. // Wait a little bit more just to be sure that we
  1160. // won't miss the extension installation
  1161. setTimeout(
  1162. () => {
  1163. DSExternalInstallationInProgress = false;
  1164. },
  1165. 500);
  1166. APP.UI.removeListener(
  1167. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1168. listener);
  1169. };
  1170. APP.UI.addListener(
  1171. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1172. listener);
  1173. APP.UI.showExtensionExternalInstallationDialog(url);
  1174. break;
  1175. }
  1176. case "extensionFound":
  1177. // Close the dialog.
  1178. externalInstallation && $.prompt.close();
  1179. break;
  1180. default:
  1181. // Unknown status
  1182. }
  1183. }
  1184. }
  1185. }).then(([desktopStream]) => {
  1186. // Stores the "untoggle" handler which remembers whether was
  1187. // there any video before and whether was it muted.
  1188. this._untoggleScreenSharing
  1189. = this._turnScreenSharingOff
  1190. .bind(this, didHaveVideo, wasVideoMuted);
  1191. desktopStream.on(
  1192. TrackEvents.LOCAL_TRACK_STOPPED,
  1193. () => {
  1194. // If the stream was stopped during screen sharing
  1195. // session then we should switch back to video.
  1196. this.isSharingScreen
  1197. && this._untoggleScreenSharing
  1198. && this._untoggleScreenSharing();
  1199. }
  1200. );
  1201. // close external installation dialog on success.
  1202. externalInstallation && $.prompt.close();
  1203. return desktopStream;
  1204. }, error => {
  1205. DSExternalInstallationInProgress = false;
  1206. // close external installation dialog on success.
  1207. externalInstallation && $.prompt.close();
  1208. throw error;
  1209. });
  1210. },
  1211. /**
  1212. * Tries to switch to the screenshairng mode by disposing camera stream and
  1213. * replacing it with a desktop one.
  1214. *
  1215. * @param {Object} [options] - Screen sharing options that will be passed to
  1216. * createLocalTracks.
  1217. *
  1218. * @return {Promise} - A Promise resolved if the operation succeeds or
  1219. * rejected with some unknown type of error in case it fails. Promise will
  1220. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1221. *
  1222. * @private
  1223. */
  1224. _switchToScreenSharing(options = {}) {
  1225. if (this.videoSwitchInProgress) {
  1226. return Promise.reject('Switch in progress.');
  1227. }
  1228. this.videoSwitchInProgress = true;
  1229. return this._createDesktopTrack(options).then(stream => {
  1230. return this.useVideoStream(stream);
  1231. }).then(() => {
  1232. this.videoSwitchInProgress = false;
  1233. JitsiMeetJS.analytics.sendEvent('conference.sharingDesktop.start');
  1234. logger.log('sharing local desktop');
  1235. }).catch(error => {
  1236. this.videoSwitchInProgress = false;
  1237. // Pawel: With this call I'm trying to preserve the original
  1238. // behaviour although it is not clear why would we "untoggle"
  1239. // on failure. I suppose it was to restore video in case there
  1240. // was some problem during "this.useVideoStream(desktopStream)".
  1241. // It's important to note that the handler will not be available
  1242. // if we fail early on trying to get desktop media (which makes
  1243. // sense, because the camera video is still being used, so
  1244. // nothing to "untoggle").
  1245. if (this._untoggleScreenSharing) {
  1246. this._untoggleScreenSharing();
  1247. }
  1248. // FIXME the code inside of _handleScreenSharingError is
  1249. // asynchronous, but does not return a Promise and is not part of
  1250. // the current Promise chain.
  1251. this._handleScreenSharingError(error);
  1252. });
  1253. },
  1254. /**
  1255. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1256. * trying to create screensharing track. It will either do nothing if
  1257. * the dialog was canceled on user's request or display inline installation
  1258. * dialog and ask the user to install the extension, once the extension is
  1259. * installed it will switch the conference to screensharing. The last option
  1260. * is that an unrecoverable error dialog will be displayed.
  1261. * @param {JitsiTrackError} error - The error returned by
  1262. * {@link _createDesktopTrack} Promise.
  1263. * @private
  1264. */
  1265. _handleScreenSharingError(error) {
  1266. if (error.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1267. return;
  1268. }
  1269. logger.error('failed to share local desktop', error);
  1270. if (error.name === TrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1271. // If start with screen sharing the extension will fail to install
  1272. // (if not found), because the request has been triggered by the
  1273. // script. Show a dialog which asks user to click "install" and try
  1274. // again switching to the screen sharing.
  1275. APP.UI.showExtensionInlineInstallationDialog(
  1276. () => {
  1277. this.toggleScreenSharing();
  1278. }
  1279. );
  1280. return;
  1281. } else if (error.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1282. APP.UI.showExtensionRequiredDialog(
  1283. config.desktopSharingFirefoxExtensionURL
  1284. );
  1285. return;
  1286. }
  1287. // Handling:
  1288. // TrackErrors.PERMISSION_DENIED
  1289. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1290. // TrackErrors.GENERAL
  1291. // and any other
  1292. let dialogTxt;
  1293. let dialogTitleKey;
  1294. if (error.name === TrackErrors.PERMISSION_DENIED) {
  1295. dialogTxt = APP.translation.generateTranslationHTML(
  1296. "dialog.screenSharingPermissionDeniedError");
  1297. dialogTitleKey = "dialog.error";
  1298. } else {
  1299. dialogTxt = APP.translation.generateTranslationHTML(
  1300. "dialog.failtoinstall");
  1301. dialogTitleKey = "dialog.permissionDenied";
  1302. }
  1303. APP.UI.messageHandler.openDialog(dialogTitleKey, dialogTxt, false);
  1304. },
  1305. /**
  1306. * Setup interaction between conference and UI.
  1307. */
  1308. _setupListeners() {
  1309. // add local streams when joined to the conference
  1310. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1311. APP.store.dispatch(conferenceJoined(room));
  1312. APP.UI.mucJoined();
  1313. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1314. APP.UI.markVideoInterrupted(false);
  1315. });
  1316. room.on(
  1317. ConferenceEvents.CONFERENCE_LEFT,
  1318. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1319. room.on(
  1320. ConferenceEvents.AUTH_STATUS_CHANGED,
  1321. (authEnabled, authLogin) =>
  1322. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1323. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1324. user => APP.UI.onUserFeaturesChanged(user));
  1325. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1326. if (user.isHidden())
  1327. return;
  1328. APP.store.dispatch(participantJoined({
  1329. id,
  1330. name: user.getDisplayName(),
  1331. role: user.getRole()
  1332. }));
  1333. logger.log('USER %s connnected', id, user);
  1334. APP.API.notifyUserJoined(id);
  1335. APP.UI.addUser(user);
  1336. // check the roles for the new user and reflect them
  1337. APP.UI.updateUserRole(user);
  1338. updateRemoteThumbnailsVisibility();
  1339. });
  1340. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1341. APP.store.dispatch(participantLeft(id, user));
  1342. logger.log('USER %s LEFT', id, user);
  1343. APP.API.notifyUserLeft(id);
  1344. APP.UI.removeUser(id, user.getDisplayName());
  1345. APP.UI.onSharedVideoStop(id);
  1346. updateRemoteThumbnailsVisibility();
  1347. });
  1348. room.on(ConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1349. let user = room.getParticipantById(id);
  1350. if (user) {
  1351. APP.UI.updateUserStatus(user, status);
  1352. }
  1353. });
  1354. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1355. if (this.isLocalId(id)) {
  1356. logger.info(`My role changed, new role: ${role}`);
  1357. APP.store.dispatch(localParticipantRoleChanged(role));
  1358. if (this.isModerator !== room.isModerator()) {
  1359. this.isModerator = room.isModerator();
  1360. APP.UI.updateLocalRole(room.isModerator());
  1361. }
  1362. } else {
  1363. APP.store.dispatch(participantRoleChanged(id, role));
  1364. let user = room.getParticipantById(id);
  1365. if (user) {
  1366. APP.UI.updateUserRole(user);
  1367. }
  1368. }
  1369. });
  1370. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1371. if(!track || track.isLocal())
  1372. return;
  1373. APP.store.dispatch(trackAdded(track));
  1374. });
  1375. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1376. if(!track || track.isLocal())
  1377. return;
  1378. APP.store.dispatch(trackRemoved(track));
  1379. });
  1380. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1381. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1382. lvl = 0;
  1383. }
  1384. if(config.debug)
  1385. {
  1386. this.audioLevelsMap[id] = lvl;
  1387. if(config.debugAudioLevels)
  1388. logger.log("AudioLevel:" + id + "/" + lvl);
  1389. }
  1390. APP.UI.setAudioLevel(id, lvl);
  1391. });
  1392. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1393. APP.UI.showToolbar(6000);
  1394. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1395. });
  1396. room.on(
  1397. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1398. (leavingIds, enteringIds) => {
  1399. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1400. });
  1401. room.on(
  1402. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1403. id => {
  1404. APP.UI.participantConnectionStatusChanged(id);
  1405. });
  1406. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1407. if (this.isLocalId(id)) {
  1408. this.isDominantSpeaker = true;
  1409. this.setRaisedHand(false);
  1410. } else {
  1411. this.isDominantSpeaker = false;
  1412. var participant = room.getParticipantById(id);
  1413. if (participant) {
  1414. APP.UI.setRaisedHandStatus(participant, false);
  1415. }
  1416. }
  1417. APP.UI.markDominantSpeaker(id);
  1418. });
  1419. if (!interfaceConfig.filmStripOnly) {
  1420. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1421. APP.UI.markVideoInterrupted(true);
  1422. });
  1423. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1424. APP.UI.markVideoInterrupted(false);
  1425. });
  1426. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1427. let nick = getDisplayName(id);
  1428. APP.API.notifyReceivedChatMessage({
  1429. id,
  1430. nick,
  1431. body,
  1432. ts
  1433. });
  1434. APP.UI.addMessage(id, nick, body, ts);
  1435. });
  1436. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1437. APP.API.notifySendingChatMessage(message);
  1438. room.sendTextMessage(message);
  1439. });
  1440. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1441. try {
  1442. // do not try to select participant if there is none (we
  1443. // are alone in the room), otherwise an error will be
  1444. // thrown cause reporting mechanism is not available
  1445. // (datachannels currently)
  1446. if (room.getParticipants().length === 0)
  1447. return;
  1448. room.selectParticipant(id);
  1449. } catch (e) {
  1450. JitsiMeetJS.analytics.sendEvent(
  1451. 'selectParticipant.failed');
  1452. reportError(e);
  1453. }
  1454. });
  1455. APP.UI.addListener(
  1456. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1457. () => this._displayAudioOnlyTooltip('videoMute'));
  1458. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1459. (smallVideo, isPinned) => {
  1460. let smallVideoId = smallVideo.getId();
  1461. let isLocal = APP.conference.isLocalId(smallVideoId);
  1462. let eventName
  1463. = (isPinned ? "pinned" : "unpinned") + "." +
  1464. (isLocal ? "local" : "remote");
  1465. let participantCount = room.getParticipantCount();
  1466. JitsiMeetJS.analytics.sendEvent(
  1467. eventName,
  1468. { value: participantCount });
  1469. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1470. // the participant is on the large video ?
  1471. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1472. && !isLocal) {
  1473. // When the library starts supporting multiple pins we
  1474. // would pass the isPinned parameter together with the
  1475. // identifier, but currently we send null to indicate that
  1476. // we unpin the last pinned.
  1477. try {
  1478. room.pinParticipant(isPinned ? smallVideoId : null);
  1479. } catch (e) {
  1480. reportError(e);
  1481. }
  1482. }
  1483. updateRemoteThumbnailsVisibility();
  1484. });
  1485. }
  1486. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1487. APP.UI.showLocalConnectionInterrupted(true);
  1488. });
  1489. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1490. APP.UI.showLocalConnectionInterrupted(false);
  1491. });
  1492. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1493. const formattedDisplayName
  1494. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1495. APP.store.dispatch(participantUpdated({
  1496. id,
  1497. name: formattedDisplayName
  1498. }));
  1499. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1500. APP.UI.changeDisplayName(id, formattedDisplayName);
  1501. });
  1502. room.on(
  1503. ConferenceEvents.LOCK_STATE_CHANGED,
  1504. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1505. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1506. (participant, name, oldValue, newValue) => {
  1507. if (name === "raisedHand") {
  1508. APP.UI.setRaisedHandStatus(participant, newValue);
  1509. }
  1510. });
  1511. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1512. logger.log("Received recorder status change: ", status, error);
  1513. APP.UI.updateRecordingState(status);
  1514. });
  1515. room.on(ConferenceEvents.KICKED, () => {
  1516. APP.UI.hideStats();
  1517. APP.UI.notifyKicked();
  1518. // FIXME close
  1519. });
  1520. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1521. APP.store.dispatch(suspendDetected());
  1522. // After wake up, we will be in a state where conference is left
  1523. // there will be dialog shown to user.
  1524. // We do not want video/audio as we show an overlay and after it
  1525. // user need to rejoin or close, while waking up we can detect
  1526. // camera wakeup as a problem with device.
  1527. // We also do not care about device change, which happens
  1528. // on resume after suspending PC.
  1529. if (this.deviceChangeListener)
  1530. JitsiMeetJS.mediaDevices.removeEventListener(
  1531. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1532. this.deviceChangeListener);
  1533. // stop local video
  1534. if (localVideo) {
  1535. localVideo.dispose();
  1536. }
  1537. // stop local audio
  1538. if (localAudio) {
  1539. localAudio.dispose();
  1540. }
  1541. });
  1542. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1543. APP.UI.updateDTMFSupport(isDTMFSupported);
  1544. });
  1545. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1546. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1547. if (this.isAudioOnly() && !muted) {
  1548. this._displayAudioOnlyTooltip('videoMute');
  1549. } else if (!localVideo && this.videoMuted && !muted) {
  1550. // Maybe try to create local video if there wasn't any ?
  1551. // This handles the case when user joined with no video
  1552. // (dismissed screen sharing screen), but decided to add it
  1553. // later on by clicking on muted video icon.
  1554. createLocalTracks({ devices: ['video'] }, false)
  1555. .then(([videoTrack]) => {
  1556. APP.conference.useVideoStream(videoTrack);
  1557. })
  1558. .catch(error => {
  1559. APP.UI.showDeviceErrorDialog(null, error);
  1560. });
  1561. } else {
  1562. muteLocalVideo(muted);
  1563. }
  1564. });
  1565. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1566. (stats) => {
  1567. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1568. });
  1569. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1570. (id, stats) => {
  1571. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1572. });
  1573. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1574. APP.UI.initEtherpad(value);
  1575. });
  1576. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1577. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1578. APP.store.dispatch(participantUpdated({
  1579. id: from,
  1580. email: data.value
  1581. }));
  1582. APP.UI.setUserEmail(from, data.value);
  1583. });
  1584. room.addCommandListener(
  1585. this.commands.defaults.AVATAR_URL,
  1586. (data, from) => {
  1587. APP.store.dispatch(
  1588. participantUpdated({
  1589. id: from,
  1590. avatarURL: data.value
  1591. }));
  1592. APP.UI.setUserAvatarUrl(from, data.value);
  1593. });
  1594. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1595. (data, from) => {
  1596. APP.store.dispatch(
  1597. participantUpdated({
  1598. id: from,
  1599. avatarID: data.value
  1600. }));
  1601. APP.UI.setUserAvatarID(from, data.value);
  1602. });
  1603. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1604. this.changeLocalDisplayName.bind(this));
  1605. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1606. (startAudioMuted, startVideoMuted) => {
  1607. room.setStartMutedPolicy({
  1608. audio: startAudioMuted,
  1609. video: startVideoMuted
  1610. });
  1611. }
  1612. );
  1613. room.on(
  1614. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1615. ({ audio, video }) => {
  1616. APP.UI.onStartMutedChanged(audio, video);
  1617. }
  1618. );
  1619. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1620. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1621. && APP.UI.notifyInitiallyMuted();
  1622. });
  1623. room.on(
  1624. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1625. APP.UI.updateDevicesAvailability(id, devices);
  1626. }
  1627. );
  1628. // call hangup
  1629. APP.UI.addListener(UIEvents.HANGUP, () => {
  1630. this.hangup(true);
  1631. });
  1632. // logout
  1633. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1634. AuthHandler.logout(room).then(url => {
  1635. if (url) {
  1636. UIUtil.redirect(url);
  1637. } else {
  1638. this.hangup(true);
  1639. }
  1640. });
  1641. });
  1642. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1643. (id, oldResolution, newResolution, delay) => {
  1644. var logObject = {
  1645. id: "resolution_change",
  1646. participant: id,
  1647. oldValue: oldResolution,
  1648. newValue: newResolution,
  1649. delay: delay
  1650. };
  1651. room.sendApplicationLog(JSON.stringify(logObject));
  1652. // We only care about the delay between simulcast streams.
  1653. // Longer delays will be caused by something else and will just
  1654. // poison the data.
  1655. if (delay < 2000) {
  1656. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1657. {value: delay});
  1658. }
  1659. });
  1660. // Starts or stops the recording for the conference.
  1661. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1662. room.toggleRecording(options);
  1663. });
  1664. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1665. room.setSubject(topic);
  1666. });
  1667. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1668. APP.UI.setSubject(subject);
  1669. });
  1670. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1671. room.kickParticipant(id);
  1672. });
  1673. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1674. room.muteParticipant(id);
  1675. });
  1676. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1677. AuthHandler.authenticate(room);
  1678. });
  1679. APP.UI.addListener(
  1680. UIEvents.VIDEO_DEVICE_CHANGED,
  1681. (cameraDeviceId) => {
  1682. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1683. createLocalTracks({
  1684. devices: ['video'],
  1685. cameraDeviceId: cameraDeviceId,
  1686. micDeviceId: null
  1687. })
  1688. .then(([stream]) => {
  1689. if (this.isAudioOnly()) {
  1690. return stream.mute()
  1691. .then(() => stream);
  1692. }
  1693. return stream;
  1694. })
  1695. .then(stream => {
  1696. this.useVideoStream(stream);
  1697. logger.log('switched local video device');
  1698. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1699. })
  1700. .catch((err) => {
  1701. APP.UI.showDeviceErrorDialog(null, err);
  1702. });
  1703. }
  1704. );
  1705. APP.UI.addListener(
  1706. UIEvents.AUDIO_DEVICE_CHANGED,
  1707. (micDeviceId) => {
  1708. JitsiMeetJS.analytics.sendEvent(
  1709. 'settings.changeDevice.audioIn');
  1710. createLocalTracks({
  1711. devices: ['audio'],
  1712. cameraDeviceId: null,
  1713. micDeviceId: micDeviceId
  1714. })
  1715. .then(([stream]) => {
  1716. this.useAudioStream(stream);
  1717. logger.log('switched local audio device');
  1718. APP.settings.setMicDeviceId(micDeviceId, true);
  1719. })
  1720. .catch((err) => {
  1721. APP.UI.showDeviceErrorDialog(err, null);
  1722. });
  1723. }
  1724. );
  1725. APP.UI.addListener(
  1726. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1727. (audioOutputDeviceId) => {
  1728. JitsiMeetJS.analytics.sendEvent(
  1729. 'settings.changeDevice.audioOut');
  1730. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1731. .then(() => logger.log('changed audio output device'))
  1732. .catch((err) => {
  1733. logger.warn('Failed to change audio output device. ' +
  1734. 'Default or previously set audio output device ' +
  1735. 'will be used instead.', err);
  1736. });
  1737. }
  1738. );
  1739. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1740. muteLocalVideo(audioOnly);
  1741. // Immediately update the UI by having remote videos and the large
  1742. // video update themselves instead of waiting for some other event
  1743. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1744. // There is no guarantee another event will trigger the update
  1745. // immediately and in all situations, for example because a remote
  1746. // participant is having connection trouble so no status changes.
  1747. APP.UI.updateAllVideos();
  1748. });
  1749. APP.UI.addListener(
  1750. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1751. );
  1752. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1753. (url, state, time, isMuted, volume) => {
  1754. // send start and stop commands once, and remove any updates
  1755. // that had left
  1756. if (state === 'stop' || state === 'start' || state === 'playing') {
  1757. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1758. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1759. value: url,
  1760. attributes: {
  1761. state: state,
  1762. time: time,
  1763. muted: isMuted,
  1764. volume: volume
  1765. }
  1766. });
  1767. }
  1768. else {
  1769. // in case of paused, in order to allow late users to join
  1770. // paused
  1771. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1772. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1773. value: url,
  1774. attributes: {
  1775. state: state,
  1776. time: time,
  1777. muted: isMuted,
  1778. volume: volume
  1779. }
  1780. });
  1781. }
  1782. updateRemoteThumbnailsVisibility();
  1783. });
  1784. room.addCommandListener(
  1785. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1786. if (attributes.state === 'stop') {
  1787. APP.UI.onSharedVideoStop(id, attributes);
  1788. }
  1789. else if (attributes.state === 'start') {
  1790. APP.UI.onSharedVideoStart(id, value, attributes);
  1791. }
  1792. else if (attributes.state === 'playing'
  1793. || attributes.state === 'pause') {
  1794. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1795. }
  1796. });
  1797. function updateRemoteThumbnailsVisibility() {
  1798. const localUserId = APP.conference.getMyUserId();
  1799. const remoteParticipantsCount = room.getParticipantCount() - 1;
  1800. // Get the remote thumbnail count for cases where there are
  1801. // non-participants displaying video, such as with video sharing.
  1802. const remoteVideosCount = APP.UI.getRemoteVideosCount();
  1803. const shouldShowRemoteThumbnails = interfaceConfig.filmStripOnly
  1804. || (APP.UI.isPinned(localUserId) && remoteVideosCount)
  1805. || remoteVideosCount > 1
  1806. || remoteParticipantsCount !== remoteVideosCount;
  1807. APP.UI.setRemoteThumbnailsVisibility(
  1808. Boolean(shouldShowRemoteThumbnails));
  1809. }
  1810. },
  1811. /**
  1812. * Adds any room listener.
  1813. * @param {string} eventName one of the ConferenceEvents
  1814. * @param {Function} listener the function to be called when the event
  1815. * occurs
  1816. */
  1817. addConferenceListener(eventName, listener) {
  1818. room.on(eventName, listener);
  1819. },
  1820. /**
  1821. * Removes any room listener.
  1822. * @param {string} eventName one of the ConferenceEvents
  1823. * @param {Function} listener the listener to be removed.
  1824. */
  1825. removeConferenceListener(eventName, listener) {
  1826. room.off(eventName, listener);
  1827. },
  1828. /**
  1829. * Inits list of current devices and event listener for device change.
  1830. * @private
  1831. */
  1832. _initDeviceList() {
  1833. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  1834. .then(isDeviceListAvailable => {
  1835. if (isDeviceListAvailable
  1836. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1837. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1838. // Ugly way to synchronize real device IDs with local
  1839. // storage and settings menu. This is a workaround until
  1840. // getConstraints() method will be implemented
  1841. // in browsers.
  1842. if (localAudio) {
  1843. APP.settings.setMicDeviceId(
  1844. localAudio.getDeviceId(), false);
  1845. }
  1846. if (localVideo) {
  1847. APP.settings.setCameraDeviceId(
  1848. localVideo.getDeviceId(), false);
  1849. }
  1850. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1851. APP.UI.onAvailableDevicesChanged(devices);
  1852. APP.store.dispatch(updateDeviceList(devices));
  1853. this.updateVideoIconEnabled();
  1854. });
  1855. this.deviceChangeListener = (devices) =>
  1856. window.setTimeout(
  1857. () => this._onDeviceListChanged(devices), 0);
  1858. JitsiMeetJS.mediaDevices.addEventListener(
  1859. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1860. this.deviceChangeListener);
  1861. }
  1862. })
  1863. .catch((error) => {
  1864. logger.warn(`Error getting device list: ${error}`);
  1865. });
  1866. },
  1867. /**
  1868. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1869. * handle change of available media devices.
  1870. * @private
  1871. * @param {MediaDeviceInfo[]} devices
  1872. * @returns {Promise}
  1873. */
  1874. _onDeviceListChanged(devices) {
  1875. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1876. // Event handler can be fired before direct
  1877. // enumerateDevices() call, so handle this situation here.
  1878. if (!currentDevices.audioinput &&
  1879. !currentDevices.videoinput &&
  1880. !currentDevices.audiooutput) {
  1881. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1882. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1883. }
  1884. let newDevices =
  1885. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1886. devices, this.isSharingScreen, localVideo, localAudio);
  1887. let promises = [];
  1888. let audioWasMuted = this.audioMuted;
  1889. let videoWasMuted = this.videoMuted;
  1890. let availableAudioInputDevices =
  1891. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1892. let availableVideoInputDevices =
  1893. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1894. if (typeof newDevices.audiooutput !== 'undefined') {
  1895. // Just ignore any errors in catch block.
  1896. promises.push(APP.settings
  1897. .setAudioOutputDeviceId(newDevices.audiooutput)
  1898. .catch());
  1899. }
  1900. promises.push(
  1901. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1902. createLocalTracks,
  1903. newDevices.videoinput,
  1904. newDevices.audioinput)
  1905. .then(tracks =>
  1906. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1907. .then(() => {
  1908. // If audio was muted before, or we unplugged current device
  1909. // and selected new one, then mute new audio track.
  1910. if (audioWasMuted ||
  1911. currentDevices.audioinput.length >
  1912. availableAudioInputDevices.length) {
  1913. muteLocalAudio(true);
  1914. }
  1915. // If video was muted before, or we unplugged current device
  1916. // and selected new one, then mute new video track.
  1917. if (!this.isSharingScreen &&
  1918. (videoWasMuted ||
  1919. currentDevices.videoinput.length >
  1920. availableVideoInputDevices.length)) {
  1921. muteLocalVideo(true);
  1922. }
  1923. }));
  1924. return Promise.all(promises)
  1925. .then(() => {
  1926. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1927. APP.UI.onAvailableDevicesChanged(devices);
  1928. this.updateVideoIconEnabled();
  1929. });
  1930. },
  1931. /**
  1932. * Determines whether or not the video button should be enabled.
  1933. */
  1934. updateVideoIconEnabled() {
  1935. const videoMediaDevices
  1936. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  1937. const videoDeviceCount
  1938. = videoMediaDevices ? videoMediaDevices.length : 0;
  1939. // The video functionality is considered available if there are any
  1940. // video devices detected or if there is local video stream already
  1941. // active which could be either screensharing stream or a video track
  1942. // created before the permissions were rejected (through browser
  1943. // config).
  1944. const available = videoDeviceCount > 0 || Boolean(localVideo);
  1945. logger.debug(
  1946. 'Camera button enabled: ' + available,
  1947. 'local video: ' + localVideo,
  1948. 'video devices: ' + videoMediaDevices,
  1949. 'device count: ' + videoDeviceCount);
  1950. APP.store.dispatch(setVideoAvailable(available));
  1951. },
  1952. /**
  1953. * Toggles the local "raised hand" status.
  1954. */
  1955. maybeToggleRaisedHand() {
  1956. this.setRaisedHand(!this.isHandRaised);
  1957. },
  1958. /**
  1959. * Sets the local "raised hand" status to a particular value.
  1960. */
  1961. setRaisedHand(raisedHand) {
  1962. if (raisedHand !== this.isHandRaised)
  1963. {
  1964. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1965. this.isHandRaised = raisedHand;
  1966. // Advertise the updated status
  1967. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1968. // Update the view
  1969. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1970. }
  1971. },
  1972. /**
  1973. * Log event to callstats and analytics.
  1974. * @param {string} name the event name
  1975. * @param {int} value the value (it's int because google analytics supports
  1976. * only int).
  1977. * @param {string} label short text which provides more info about the event
  1978. * which allows to distinguish between few event cases of the same name
  1979. * NOTE: Should be used after conference.init
  1980. */
  1981. logEvent(name, value, label) {
  1982. if(JitsiMeetJS.analytics) {
  1983. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1984. }
  1985. if(room) {
  1986. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1987. }
  1988. },
  1989. /**
  1990. * Methods logs an application event given in the JSON format.
  1991. * @param {string} logJSON an event to be logged in JSON format
  1992. */
  1993. logJSON(logJSON) {
  1994. if (room) {
  1995. room.sendApplicationLog(logJSON);
  1996. }
  1997. },
  1998. /**
  1999. * Disconnect from the conference and optionally request user feedback.
  2000. * @param {boolean} [requestFeedback=false] if user feedback should be
  2001. * requested
  2002. */
  2003. hangup(requestFeedback = false) {
  2004. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2005. let requestFeedbackPromise = requestFeedback
  2006. ? APP.UI.requestFeedbackOnHangup()
  2007. // false - because the thank you dialog shouldn't be displayed
  2008. .catch(() => Promise.resolve(false))
  2009. : Promise.resolve(true);// true - because the thank you dialog
  2010. //should be displayed
  2011. // All promises are returning Promise.resolve to make Promise.all to
  2012. // be resolved when both Promises are finished. Otherwise Promise.all
  2013. // will reject on first rejected Promise and we can redirect the page
  2014. // before all operations are done.
  2015. Promise.all([
  2016. requestFeedbackPromise,
  2017. room.leave().then(disconnect, disconnect)
  2018. ]).then(values => {
  2019. APP.API.notifyReadyToClose();
  2020. maybeRedirectToWelcomePage(values[0]);
  2021. });
  2022. },
  2023. /**
  2024. * Changes the email for the local user
  2025. * @param email {string} the new email
  2026. */
  2027. changeLocalEmail(email = '') {
  2028. email = String(email).trim();
  2029. if (email === APP.settings.getEmail()) {
  2030. return;
  2031. }
  2032. const localId = room ? room.myUserId() : undefined;
  2033. APP.store.dispatch(participantUpdated({
  2034. id: localId,
  2035. local: true,
  2036. email
  2037. }));
  2038. APP.settings.setEmail(email);
  2039. APP.UI.setUserEmail(localId, email);
  2040. sendData(commands.EMAIL, email);
  2041. },
  2042. /**
  2043. * Changes the avatar url for the local user
  2044. * @param url {string} the new url
  2045. */
  2046. changeLocalAvatarUrl(url = '') {
  2047. url = String(url).trim();
  2048. if (url === APP.settings.getAvatarUrl()) {
  2049. return;
  2050. }
  2051. const localId = room ? room.myUserId() : undefined;
  2052. APP.store.dispatch(participantUpdated({
  2053. id: localId,
  2054. local: true,
  2055. avatarURL: url
  2056. }));
  2057. APP.settings.setAvatarUrl(url);
  2058. APP.UI.setUserAvatarUrl(localId, url);
  2059. sendData(commands.AVATAR_URL, url);
  2060. },
  2061. /**
  2062. * Sends a message via the data channel.
  2063. * @param {string} to the id of the endpoint that should receive the
  2064. * message. If "" - the message will be sent to all participants.
  2065. * @param {object} payload the payload of the message.
  2066. * @throws NetworkError or InvalidStateError or Error if the operation
  2067. * fails.
  2068. */
  2069. sendEndpointMessage(to, payload) {
  2070. room.sendEndpointMessage(to, payload);
  2071. },
  2072. /**
  2073. * Adds new listener.
  2074. * @param {String} eventName the name of the event
  2075. * @param {Function} listener the listener.
  2076. */
  2077. addListener(eventName, listener) {
  2078. eventEmitter.addListener(eventName, listener);
  2079. },
  2080. /**
  2081. * Removes listener.
  2082. * @param {String} eventName the name of the event that triggers the
  2083. * listener
  2084. * @param {Function} listener the listener.
  2085. */
  2086. removeListener(eventName, listener) {
  2087. eventEmitter.removeListener(eventName, listener);
  2088. },
  2089. /**
  2090. * Changes the display name for the local user
  2091. * @param nickname {string} the new display name
  2092. */
  2093. changeLocalDisplayName(nickname = '') {
  2094. const formattedNickname
  2095. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2096. if (formattedNickname === APP.settings.getDisplayName()) {
  2097. return;
  2098. }
  2099. APP.store.dispatch(participantUpdated({
  2100. id: this.getMyUserId(),
  2101. local: true,
  2102. name: formattedNickname
  2103. }));
  2104. APP.settings.setDisplayName(formattedNickname);
  2105. if (room) {
  2106. room.setDisplayName(formattedNickname);
  2107. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  2108. }
  2109. },
  2110. /**
  2111. * Returns the desktop sharing source id or undefined if the desktop sharing
  2112. * is not active at the moment.
  2113. *
  2114. * @returns {string|undefined} - The source id. If the track is not desktop
  2115. * track or the source id is not available, undefined will be returned.
  2116. */
  2117. getDesktopSharingSourceId() {
  2118. return localVideo.sourceId;
  2119. },
  2120. /**
  2121. * Returns the desktop sharing source type or undefined if the desktop
  2122. * sharing is not active at the moment.
  2123. *
  2124. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2125. * not desktop track or the source type is not available, undefined will be
  2126. * returned.
  2127. */
  2128. getDesktopSharingSourceType() {
  2129. return localVideo.sourceType;
  2130. }
  2131. };