Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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