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

conference.js 81KB

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